How to make an element fill its container using CSS?
P粉514458863
P粉514458863 2024-02-21 16:48:39
0
2
354

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粉514458863
P粉514458863

reply all(2)
P粉333395496

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
P粉071602406

DIV
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!