CSS position relative without relative width?

微笑、不失礼 提交于 2019-12-24 17:23:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!