【问题标题】:Why does changing position from relative to absolute change the background image size?为什么从相对位置更改为绝对位置会更改背景图像大小?
【发布时间】:2015-04-04 09:27:56
【问题描述】:

我有以下 html 和 css。如果我将位置属性从绝对更改为相对,div.raw 似乎在 html 布局中流动,并且背景图像不会覆盖所有内容。如果我不这样做,那么它会这样做。这是为什么呢?

HTML:

<h1 class="push">Hello World</h1>
<div class="container">
  Some text
<div class="raw"></div>
</div>

CSS:

.push {
  margin-bottom: 50px;
  margin-top: 50px;
}
.container {
  margin-top: 50px;
  width: 500px;
  height: 500px;
  margin-bottom: 50px;
}
.raw {
  border: 1px solid black;
  position: absolute;
  top: 0;
  left: 0;
  background-size: auto;
  background-image: url("http://st-im.kinopoisk.ru/im/wallpaper/2/3/0/kinopoisk.ru-True-Detective-2300505--w--1280.jpg");
  //background-repeat: no-repeat;
  overflow: hidden;
  width: 50%;
  height: 100%;}

【问题讨论】:

    标签: html css


    【解决方案1】:

    绝对定位元素位置固定到它们需要定位的祖先。在您的情况下,祖先“容器”没有位置,因此 div.raw 将自身定位为固定到视口。实际上,如果您将 raw 的位置设置为固定,您会发现它与绝对位置相同。但是,一旦您将位置设置为容器(例如相对),那么绝对和固定就会有所不同。

    这里的结果与绝对值相同

    http://jsfiddle.net/btevfik/0ugp2p2w/2/

    一旦你放了这个

    .container {
          position:relative;
    }
    

    注意结果不同

    http://jsfiddle.net/btevfik/0ugp2p2w/

    http://jsfiddle.net/btevfik/0ugp2p2w/1/

    http://jsfiddle.net/btevfik/0ugp2p2w/3/

    【讨论】:

      【解决方案2】:

      因为绝对定位元素的相对尺寸与整个文档相关,所以相对定位元素的相对尺寸与其父元素相关。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-09-01
        • 2019-03-15
        • 1970-01-01
        • 1970-01-01
        • 2012-04-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多