Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force division into equal parts using flexbox

Tags:

html

css

flexbox

In a dom structure like this:

<div id="1">
  <div id="2">
    <div id="3">
    </div>
  </div>
  <div id="4">
    <div id="5">
    </div>
  </div>
</div>

with css specified as:

#1{
  display: flex;
  flex-direction: row;
}
#2, #4{
  flex: 1;
}

The divs with id 2 and 4 will be evenly distributed as long as the sum of the width of the contents in id 3 and 5 does not exceed the width of the dom with id 1.

When the sum exceeds the width, they are not evenly distributed, and one with wider content will take up more width. How can I force 2 and 4 to take up even width using flexbox even in such cases?

I do not want to use width specification by percent. I want to stick to flexbox.

like image 517
sawa Avatar asked Jun 08 '13 13:06

sawa


People also ask

How do you equally divide flexbox?

EQUAL HEIGHT + WIDTH COLUMNS WITH MARGINSAdd display:flex, justify-content: space-between; to the parent and give a width to the boxes that totals to less than 100%. E.g. These boxes have a width of 32% each.

How do you show 3 items per row in flexbox?

For 3 items per row, add on the flex items: flex-basis: 33.333333% You can also use the flex 's shorthand like the following: flex: 0 0 33.333333% => which also means flex-basis: 33.333333% .

Does flexbox work with position fixed?

position:fixed makes flexbox not workable, since it overrides the position of <p>Hello</p> Try to remove it and see the difference. If you want align-items:center works; try to set height: 100vh; since the body height of webview is not set to screen height by default.


2 Answers

If you want elements to grow or shrink independently to it's content, specify zero flex basis:

flex-basis: 0;

However, my demo incorrectly works in Chrome: large image stretches it's parent container no matter that zero basis has been set. As a workaround, maximum width can be set:

img {
  max-width: 100%;
  height: auto;
}
like image 183
Pavlo Avatar answered Sep 21 '22 08:09

Pavlo


To force the equal distribution, you have to add width: 0 to all flex items. This came to my mind after reading Manuel Matuzovic's article, which has a very good in-depth conclusion how flex-grow works.

https://css-tricks.com/flex-grow-is-weird/

like image 43
Florian Strohmaier Avatar answered Sep 20 '22 08:09

Florian Strohmaier