背景位置:将左角放在中心位置

时间:2017-01-27 12:33:22

标签: css background

希望这张图片能够解释更多,我想要的东西 bg-pos.png

(图像的透明部分应表明它大于.content Div: - )

是否有一种几乎保存的方式(最好只是CSS)让背景图像从中心开始?

background-position: center top;

...会使用图片的中心,而不是左角。

我无法操纵图像本身(使用透明偏移)也不能使用绝对值。

2 个答案:

答案 0 :(得分:2)

如果不使用绝对值,您将无法在所需元素上使用背景图像执行此操作。有关原因的说明,请参阅this answer。简而言之,具有百分比和关键字值的背景定位非常类似于滑动拼图,将图像严格保持在元素的背景定位区域内。只有绝对值才能免于此行为。

您可以通过使图像成为所需元素的伪元素的背景来作弊,但这需要相对定位所需元素并充当所有绝对定位后代的包含块,包括伪元素:

.content {
  position: relative;
  height: 200px;
  border: 1px solid;
}

.content#one { width: 100px; }
.content#two { width: 200px; }

.content::before {
  content: '';
  position: absolute;
  left: 50%;
  width: 50%;
  height: 100%;
  background: url(http://placehold.it/150x150) no-repeat;
}
<div class="content" id="one"></div>
<div class="content" id="two"></div>

答案 1 :(得分:0)

可以使用伪元素

完成

.cimg {
  border: 1px solid black;
  height: 400px;
  position: relative;
}

.cimg::after {
  content: "";
  position: absolute;
  left: 50%;
  top: 0;
  height: 100%;
  width: 50%;
  background-image: url("http://www.youramazingplaces.com/wp-content/uploads/2014/06/sunset-5.jpg");
  background-repeat: no-repeat;
  background-size: 400px;
}
<div class="cimg">

</div>