2015-04-04 56 views
1

我有以下的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%;} 

回答

0

因为绝对定位的元素的相对尺寸都与整个文档,相对定位元素的相对尺寸都与它的父元素。

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/