且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

绝对定位的div内的相对定位div

更新时间:2022-10-21 09:52:51

如果相对定位的容器中唯一的元素位于绝对位置,则必须在容器上指定高度。问题在于 position:absolue 从内容流中移除了元素,所以容器无法识别绝对定位元素的高度。


How can you contain an absolute positioned div inside a relative positioned div ? For example, a structure like this :

HTML

<div class="wrapper clearfix">
 <div class="contentWrapper">
  <div class="content">Looong text here...</div>
 </div>
</div>

CSS

.wrapper {
position:relative;
}
.contentWrapper {
position:absolute;
top:0;
left:0;
}

will result as the height of the contentWrapper to be 0 (when element inspected) and the div with the content class will not show.

Is there a way to apply clearfix method for absolute positioned elements inside relative ones ?

Thanks

Edit:

What I am trying to do here is to avoid the "Looooong text" from expanding the wrapper (wrapper has a dynamic width, cannot be fixed). contentWrapper contains the text and wraps it, also it fills the width of the parent wrapper so that it does not get expanded. The only problem is the height of the contentWrapper is 0, and the text is not showing.

Any other way to do this ?

If the only element inside your relatively positioned container is positioned absolute, you will have to specify a height on the container. The problem is that position:absolue removes the element from the content flow, so the container doesn't recognize the absolutely positioned element's height.