How can we make margin elements fill Flexbox items that are not themselves Flexbox?
An element (even a nested element with margins) can easily fill its container - if it's not inside a Flexbox item - using position:absolute
. Why doesn't this work for elements inside a Flexbox project?
<main> <nav>NAV</nav> <section> <div>DIV</div> </section> </main> <style> html, body { position:absolute; top:0; left:0; right:0; bottom:0; margin: 0; } main { position:absolute; top:0; left:0; right:0; bottom:0; display: flex; } nav { flex-basis: 250px; background-color: #eee; } section { flex-basis: 100%; background-color: #ccc; margin: 10px; } div { /* position:absolute; top:0; left:0; right:0; bottom:0; */ /* why doesn't the above line work? */ background-color: #cfc; margin: 10px; } </style>
There are many similar questions, such as this one and this one, that don't actually work for items inside a flexbox or items with margins. There are many special case solutions, such as align-self:stretch
, height:100%
and box-sizing:border-box
not in this case Works because of the nested margin
or the fact that Flexbox itself is not nested. Problems with these one-time hackers keep popping up...
So what is the general way to populate a Flexbox project? position:absolute
What's the problem here? What is the most general way to have an element fill its container?
Here are some ideas you might think are worth exploring? I treat
nav
as a brother and not a child ofmain
. This isn't necessary for CSS, but the structure makes the most sense. Ideally you haveheader
,nav``main
,footer
, and possiblyaside
. You really want to avoid all absolute positioning. It doesn't play well on mobile - imagine what would happen if you put a textbox or textarea on the page and a mobile user clicked on it and a soft keyboard popped up.