问题
Let's say I have two divs, one inside the other, like so:
<html>
<body>
<div id="outer" style="width:50%">
<div id="inner" style="width:100%">
</div>
</div>
</body>
</html>
Right now, the inner div has a width of 100% of 50% of the screen size, or 50% of the screen size. If I were to change the inner div to position absolute, like this:
<html>
<body>
<div id="outer" style="width:50%">
<div id="inner" style="position:absolute;width:100%">
</div>
</div>
</body>
</html>
In this case the inner div takes up 100% of the screen space, because its position is set to absolute.
My question is this: Is there any way to maintain relative width of the inner div while its position is set to absolute?
回答1:
Add position:relative to your outer div.
update: It works because positions in position: absolute
are relative to the first parent that has some positioning (other than static). In this case there was no such container, so it uses the page.
回答2:
Yes. Set outer to position: relative.
http://jsfiddle.net/57673/
.outer
{
width: 50%;
height: 200px;
position: relative;
border: 1px solid red;
}
.inner
{
width: 100%;
position: absolute;
height: 100%;
border: 1px solid blue;
}
来源:https://stackoverflow.com/questions/14327104/is-there-any-way-for-positionabsolute-div-to-retain-relative-width