Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent a flex item from shrinking smaller than its content?

Tags:

html

flexbox

I've set up a jsfiddle to demonstrate the problem here:
http://jsfiddle.net/x0eo3aeo/2/

HTML:

<div class="flexContainer">
    <div class="flexCol1">aaa</div>
    <div class="flexCol2"><div style="width:100px; background-color:yellow;">bbb</div></div>
    <div class="flexCol3"><div style="width:250px; background-color:pink;">Hello world, some long text here to make this element stay at 250px while splitting onto multiple lines.</div></div>
</div>

CSS:

.flexContainer {
    display: flex;
    width: 100%;
    flex-direction: row;
}
.flexCol1, .flexCol3 {
    flex: 1;
    background-color: green;
}

Firefox actually behaves exactly how I want. Columns 1 and 3 flex equally until the width of column 3 hits the fixed size of its child div, and then only column 1 is flexed. However, in Chrome, both columns continue to flex equally and the child content of column 3 overflows.

Is there a way to achieve the Firefox-style behaviour in a cross-browser way?

like image 652
Jez Avatar asked Jan 19 '15 16:01

Jez


People also ask

How do you make a flex item occupy remaining space?

Use the flex-grow property to make a flex item consume free space on the main axis. This property will expand the item as much as possible, adjusting the length to dynamic environments, such as screen re-sizing or the addition / removal of other items.

Which property identifies a flex item that can grow bigger but not shrink?

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

How do you control the flex item width?

A flexbox item can be set to a fixed width by setting 3 CSS properties — flex-basis, flex-grow & flex-shrink. flex-basis : This property specifies the initial length of the flex item. flex-grow : This property specifies how much the flex item will grow relative to the rest of the flex items.


1 Answers

You should be able to achieve the Firefox behavior in Chrome by adding min-width: -webkit-min-content; to .flexCol3. This prevents it from shrinking below its min-content width. (This is what's supposed to happen by default, due to min-width:auto introduced in the flexbox spec, but that hasn't been implemented in Chrome yet.)

As noted in comments below, IE doesn't seem to have a min-content width keyword implemented, so you might have to do something hackier there (like min-width: 250px). Fortunately, IE's next release (12?) does have min-width:auto implemented, so this should Just Work like Firefox there, I'm told.

like image 174
dholbert Avatar answered Oct 20 '22 00:10

dholbert