问题
I'd like an element to have relative positioning. But I don't want its child element (with position:absolute
) to have relative width to the parent.
For example: http://jsfiddle.net/t2yJP/. I'd like the second body>div
to have position:relative
, but have its child's width maintain the same behavior.
回答1:
How about this jsFiddle.
But you should really rethink your strategy. In your fiddle, your second example only works because the parent div is not positioned and therefore, the .abs
div is technically not in the parent.
Normally, child elements are inside their parents. That's what containers are for! So if you don't want the .abs
div to be constrained by the red rectangle, don't put it inside the red rectangle.
回答2:
Try adding width:inherit
to the .abs
class.
回答3:
I was able to achieve a similar-looking effect as follows:
<div class='abs pad'>
Content content content
</div>
<div class='rel pad red'>
</div>
.rel {
position: relative;
}
.abs {
position: absolute;
z-index: 1;
}
.pad {
padding: 2px;
margin: 2px;
}
.red {
border: 1px solid black;
width: 100px;
height: 100px;
background-color: red;
}
来源:https://stackoverflow.com/questions/10420264/css-position-relative-without-relative-width