Flex left div fill remaining space when right div is at maximum width

Viewed 18

I have two divs inside a flex box. Div A is on the left, and div B is on the right.

I would like div A to take up 60% of the flex box, and div B to take up 40% of the flex box. As you can imagine, my css will look like this:

.container {
    display: flex;
    justify-content: start; 
    flex-direction: column;
}
.div_a {
    width: 60%;
}
.div_b {
    width: 40%;
}

Also, the browser will look like this:

enter image description here

Now, I would like div B to have a maximum and minimum width, the code will now look like this:

.container {
    display: flex;
    justify-content: start; 
    flex-direction: column;
}
.div_a {
    width: 60%;
}
.div_b {
    width: 40%;
    max-width: 768px; 
    min-width: 480px; 
}

Unfortunately, this will lead to this situation large browsers.

enter image description here

When Div B has reached its maximum width, I would like div A to fill up the rest of the space, like this:

enter image description here

Any ideas or fixes would be appreciated, thank you very much in advance.

I should mention that min-width: 60% for Div A produces the same situation, unfortunately.

1 Answers

This is a perfect case where you would turn towards the property flex-grow. Since you're working with a 60%/40% size, you can use flex-grow:6 and flex-grow:4, or alternatively: flex-grow:3 and flex-grow:2. Or even: flex-grow:1.5 and flex-grow:1 since the property also accepts decimals!

.div_a {
    flex-grow:3;
}
.div_b {
    flex-grow: 2;
    max-width: 768px; 
    min-width: 480px; 
}

flex-grow is a property that will tell the parent (flexbox) to divide the available width into whatever amount of flex-grow is specified in the child elements. By limiting the max width of .div_b, you tell flexbox to stop increasing the width after it reached that max, and the remaining width will be reserved for the other elements (.div_a in this case).

Also

I do want to point out that you're using flex-direction:column, but you're trying to create a row based layout. It's a better idea to use flex-flow: row nowrap. Which is a shorthand to declare both flex-direction and flex-wrap together and, with the value row nowrap will tell the parent to force everything on one line in a horizontal layout.

.container {
    display: flex;
    justify-content: start; 
    // flex-direction: column;
    flex-flow: row nowrap;
}
Related