Home > OS >  How to set the width of the child list of a flex:auto element
How to set the width of the child list of a flex:auto element

Time:12-31

Hi I have a CSS question. There are two columns, the right (B) column has a fixed width of 100px, and the left (A) column have to fill the remaining width. Also, inside A column, there is a list of child components that are added horizontally.

The problem is, when the child component is added, A column's width becomes longer and column B goes down.

How can I make it so that when a child component is added, if it exceeds A column width, it is added to the bottom line inside A column?

  • When the number of child elements is small enter image description here
  • When the number of child elements increases (AS-IS) enter image description here
  • When the number of child elements increases (TO-BE) enter image description here

CodePudding user response:

Instead of flex you can use display grid. With grid you can define if an item should be dynamic or static.

Example:

.main {
  display: grid;
  grid-template-columns: 1fr 100px;
}
<div >
  <div >
    I am dynamic in size
  </div>
  <div >
    I'll always be 100px
  </div>
</div>

The 1fr in grid-template-columns stands for one free space, meaning all the space besides the 100px of the second element will be filled by the first item.

CodePudding user response:

Use flex-wrap on both the overall container and on A, and set the width of box A to be calc(100% - 100px).

body {
  width: 100vw;
  padding: 0;
  margin: 0;
  color: white;
}

#flex {
  display: flex;
  background-color: grey;
  width: 100vw;
  height: fit-content;
  flex-wrap: wrap;
}

#a {
  width: calc(100% - 100px);
  height: fit-content;
  background-color: red;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  align-items: center;
}

#a .x {
  width: 100px;
  margin: 10px;
  background-color: green;
  height: 200px;
}

#b {
  width: 100px;
  height: 500px;
  background-color: blue;
}
<div id="flex">
  <div id="a"> A
    <div >X</div>
    <div >X</div>
    <div >X</div>

  </div>
  <div id="b">
    B
  </div>
</div>

with 1 'X' div (ignore alignment, is because of the 'A' text; enter image description here

with 4 'X' divs: enter image description here

  • Related