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?
P粉3333954962024-02-22 16:22:19
Here are some ideas you might think are worth exploring? I treat nav
as a brother and not a child of main
. This isn't necessary for CSS, but the structure makes the most sense. Ideally you have header
, nav``main
, footer
, and possibly aside
. 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.
body { display: grid; grid-template-columns: [left] 196px [main] 1fr [right]; grid-template-rows: [top] 1fr [bottom]; grid-gap: 4px; outline: 1px dashed #616161; min-height: 100vh; min-width: 0; } body > nav { outline: 1px dashed red; grid-column-start: left; grid-column-end: main; grid-row-start: top; grid-row-end: bottom; } body > main { outline: 1px dashed blue; grid-column-start: main; grid-column-end: right; grid-row-start: top; grid-row-end: bottom; display: flex; flex-flow: column nowrap; } section { flex: 1 1 auto; display: flex; flex-flow: column nowrap; } div { flex: 1 1 auto; margin: 4px; outline: 1px dotted green; min-height: auto; }
DIV