【问题标题】:Background position: put left corner in center背景位置:左角居中
【发布时间】:2017-01-27 12:33:22
【问题描述】:

希望这张图片能解释更多,我想要什么

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

是否有一种几乎可以节省的方法(最好只是 CSS)让背景图像从中心开始?

background-position: center top;

... 将使用图像的中心,而不是左角。

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

【问题讨论】:

  • 为此您需要添加“background-size:cover”
  • 这与提问者想要的完全相反。
  • 您必须将background-position 设置为像素值(在 X 轴上)。使用关键字或百分比值,我认为这是不可能的。
  • 请提供您当前使用的代码。据我所知,没有办法单独使用background 属性来实现这一点,您可以通过使用伪元素来伪造您想要的效果。

标签: css background


【解决方案1】:

如果不使用绝对值,您将无法使用所需元素上的背景图像来执行此操作。请参阅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>

【讨论】:

    【解决方案2】:

    可以用伪元素来完成

    .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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-29
      • 2014-12-29
      相关资源
      最近更新 更多