Search code examples
cssalignmentflexbox

Flexbox evenly sized elements regardless of contents


How to size each square the same???

Preview Issue on JSBIN | View Issue Code on JSBIN

I am using flexbox to create a grid layout. Most grid cells do not have content and some grid cells do have content. When a cell has content it throws everything off. how can I make sure all cells are even regardless of content?

Not sized correctly

HTML

I have three rows, each with three cells. Only the center row of the center cell contains children.

<div>
  <div></div>
  <div></div>
  <div></div>
</div>

<div>
  <div></div>
  <div><span>contains span</span></div>
  <div></div>
</div>

<div>
  <div></div>
  <div></div>
  <div></div>
</div>

CSS

In the css the center space is larger than the other squares.

body, html {
  height: 100%;
}

body {
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
}

body>div {
  display: flex;
}

body>div>div {
  border: solid 1px blue;
}

div {
  flex-grow: 1;
}

body>div:nth-child(2)>div:nth-child(2) {
  display: flex;
  align-items: center;
  justify-content: center;
}

Solution

  • You shall use flex-basis to specify the initial length of the flexible item.

    body, html {
      height: 100%;
    }
    
    body {
      margin: 0;
      padding: 0;
      display: flex;
      flex-direction: column;
    }
    
    body>div {
      display: flex;
    }
    
    body>div>div {
      border: solid 1px blue;
    }
    
    div {
      flex-grow: 1;
       flex-basis: 80px; /*set the initial length*/
    }
    
    body>div:nth-child(2)>div:nth-child(2) {
      display: flex;
      align-items: center;
      justify-content: center;
    }
    <div>
      <div></div>
      <div></div>
      <div></div>
    </div>
    
    <div>
      <div></div>
      <div><span>contains span asdsa asd asd asd asdsad ads asd sad</span></div>
      <div></div>
    </div>
    
    <div>
      <div></div>
      <div></div>
      <div></div>
    </div>