Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flexbox evenly sized elements regardless of contents

Tags:

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; } 
like image 204
Tabbyofjudah Avatar asked Aug 09 '15 21:08

Tabbyofjudah


People also ask

How do you equally divide flex into two columns?

Use a container with display: flex and assign the width to 50% to the two parts you want to divide.

Which properties can control the size of Flex items?

The flex-shrink property. The flex-shrink property specifies the flex shrink factor, which determines how much the flex item will shrink relative to the rest of the flex items in the flex container when negative free space is distributed.


1 Answers

You are using flex-grow: 1. That means that the initial width of the flex items will be the width of its content, and then the available space will be distributed equally.

However, you want the flex items to have the same width, so you want to ignore the width of their content. You can achieve this with

flex: 1; 

Additionally, Flexbox introduces auto as the initial value of min-width. This might produce different widths in some cases, so to be safe better add min-width: 0 or set overflow to anything but visible

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: 1;    min-width: 0;  }  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</span></div>    <div></div>  </div>  <div>    <div></div>    <div></div>    <div></div>  </div>
like image 80
Oriol Avatar answered Oct 24 '22 14:10

Oriol