Francisco Romero
Francisco Romero

Reputation: 13199

Flex item override max-width property

I am trying to make a flex container of divs in which all the divs will have the same width (two divs per line, 50% width of the container each of them).

I have set the divs inside the container with max-width: 50%; because I want them to be equals but it does not seem to respect this max-width when there is only one item in this line.

HTML:

<div id="container">
  <div id="left" class="block">Left</div>
  <div id="center" class="block">
    <div class="flexContainer">
      <div class="flexDiv"></div>
    </div>
    <div class="flexContainer">
      <div class="flexDiv"></div>
    </div>
    <div class="flexContainer">
      <div class="flexDiv"></div>
    </div>
  </div>
  <div id="right" class="block">Right</div>
</div>

CSS:

html, body{
    width: 100%;
    height: 100%;
}

#container{
    display: flex;
    height: 100%;
    background-color: blue;
}

.block{
    flex: 1;
}

#left{
    background-color: green;
}

#center{
    display: flex;
    flex: 1;
    flex-wrap: wrap;  
    align-content: flex-start;
}

#right{
    background-color: orange;
}

.flexContainer{
    flex: 1;
    min-width: 100px;
    max-width: 50%;
    height: 150px;
    background-color: red;
    padding: 10px;
}

.flexDiv{
    width: 100%;
    height: 100%;
    background-color: yellow;
}

JSFiddle in which you can see how the width of the third element is bigger than the others.

Why the flex divs inside the container are not respecting max-width property?

Thanks in advance!

Upvotes: 0

Views: 5277

Answers (1)

G-Cyrillus
G-Cyrillus

Reputation: 106068

you can reset or switch box model to include padding within width calculation:

https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing

https://www.w3.org/TR/css-ui-3/#box-sizing

.flexContainer{
    flex: 1;
    min-width: 100px;
    max-width: 50%;
    height: 150px;
    background-color: red;
    padding: 10px;
    box-sizing:border-box;/* includes borders & padding within width calculation
}

https://jsfiddle.net/b5h9rjcd/1/

Upvotes: 2

Related Questions