Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flex Basis behavior not as expected but max-width works

Tags:

html

css

flexbox

I actually found a solution to my problem but would like to know why my original solution doesn't work.

I have a simple flex container in which I want the first div to be 30% of the container. I gave it a flex-basis of 30% to try to achieve this. This works until I have content that exceeds the length of 30%. At this point, it extends the div making it more than 30%.

I solved this using the max-width attribute which I found from another question after some research, but am still confused why flex-basis does not work, and would prefer not to have a max-width attribute when using flex box. I read that if flex-direction is row, flex-basis should be a replacement for width, but this does not seem to be the case.

Here is a fiddle and the css along with it: https://jsfiddle.net/jg5nbdgp/12/

.container {
  display:flex;
  flex-direction: row;

  .left {
    flex-basis: 30%;      /* This doesn't work */
    /* max-width: 30%; */ /* This works */

    .box {
      height: 50px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }

  .middle {
    flex-basis: 50%;
  }

  .right {
    flex-basis: 20%;
  }
}
like image 659
rishubk Avatar asked Sep 02 '25 06:09

rishubk


1 Answers

It is because flex box items cannot be smaller than the actual content. This is the default behaviour of flexbox.

Including min-width:0 to .left class will make flex-basis work.

So in your case your content width is greater the flex-basis value and by the default flexbox behaviour flex box width cannot be smaller than the content. By flexbox terms your code has actually become

.left {
  flex-basis: 30%;
  min-width: auto;
  max-width: auto;
}

so you have to update the width to let flexbox come over the default behaviour. update your class to

.left {
  flex-basis: 30%;
  min-width: 0;
}

In order words you can remember width values precedes the flex-basis values.

JsFiddle: https://jsfiddle.net/gLodw7k1/

like image 120
Karthick Manoharan Avatar answered Sep 04 '25 21:09

Karthick Manoharan