The width of div with absolute position depends on its parent's width?

你。 提交于 2019-12-03 08:12:49

The element gets its width and height before it gets removed from the flow of the document. When you position the outside element absolutely, it gets removed from the flow and since it has no immediate content, it has a width of 0 and height of 0. Therefore, another division element inside it attempting to add text inherits the parent's width of 0. So it's only going to expand to the width of the longest word to allow for content, and then break everything else to new lines. After it's done that, it removes the element from the flow of the document to be off on its own.

So, to answer your first question, yes, an absolutely positioned element does pay attention to its parent element's dimensions if you don't specify a width and/or height on the element itself. Do you know what the width of your children is supposed to be?

As for your second question... you can use white-space: nowrap. Not really a great solution. More preferably, find a better way to organize your content so you don't need three absolutely positioned elements nested inside each other. You say you have to use them... Really? It's more likely that you just haven't found a better way to do it, but that's for another question if you so choose to go down that road.

A block level element with position: absolute or fixed is automatically bound to its parent's width if no fixed width is set. If you don't want a fixed width for the child element, you can effectively work around this by giving it a very high margin-right, e.g.

.inner-div {
    position: absolute;
    margin-right: -10000px;
}

Then its width will be bound to the width of the parent minus the negative margin, so in practice will only depend on its content.

Updated fiddle: http://jsfiddle.net/ymgfN/53/

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