Make absolute positioned div expand parent div height

ghz 1years ago ⋅ 10303 views

Question

As you can see in the CSS below, I want child2 to position itself before child1. This is because the site I'm currently developing should also work on mobile devices, on which the child2 should be at the bottom, as it contains the navigation which I want below the content on the mobile devices.

  • Why not 2 masterpages? This is the only 2 divs which are repositioned in the entire HTML, so 2 masterpages for this minor change is an overkill.

HTML:

<div id="parent">
    <div class="child1"></div>
    <div class="child2"></div>
</div>

CSS:

parent { position: relative; width: 100%; }
child1 { width: auto; margin-left: 160px; }
child2 { width: 145px; position: absolute; top: 0px; bottom: 0px; }

child2 has dynamic height, as different subsites could have more or less navigation items.

I know that absolute positioned elements are removed from the flow, thus ignored by other elements.
I tried setting overflow:hidden; on the parent div, but that didn't help, neither does the clearfix.

My last resort will be JavaScript to reposition the two divs accordingly, but for now I'll try and see if there exist a non-JavaScript way of doing this.


Answer

You answered the question yourself:

I know that absolute positioned elements are removed from the flow, thus ignored by other elements.

So you can't set the parents height according to an absolutely positioned element.

You either use fixed heights or you need to involve JavaScript.

Nowadays one might use CSS [flexbox](https://developer.mozilla.org/en- US/docs/Web/CSS/CSS_Flexible_Box_Layout/Aligning_Items_in_a_Flex_Container#alignment_and_flex- direction) or grid layout to reverse the visual order of HTML elements inside a parent container without using position: absolute;. See also [Reverse order of columns in CSS Grid Layout](https://stackoverflow.com/questions/45383042/reverse-order-of- columns-in-css-grid-layout)