为什么从相对位置更改位置会改变背景图像大小?

时间:2015-04-04 01:08:39

标签: html css

我有以下html和css。如果我将position属性从绝对更改为relative,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%;}

2 个答案:

答案 0 :(得分:1)

绝对定位的元素位置固定在它们的祖先上,需要有一个定位。在你的情况下,祖先&#39;容器&#39;没有位置所以div.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/

答案 1 :(得分:0)

由于绝对定位元素的相对维度与整个文档相关,因此相对定位元素的相对维度与其父元素相关。

相关问题