Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping flexbox from collapsing child width when auto margins are set

Tags:

css

flexbox

I'm using flexbox to create a sticky footer.

body {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
    margin: 0;
}

header, footer {
    background-color: #c9c9c9;
    padding: 20px;
}

main {
    flex: 1;
    margin: 0 auto;
    max-width: 300px;
    border: 1px solid red;
}
<header></header>
<main>This is some content</main>
<footer></footer>

JsFiddle

This works okay, but the width of <main> now collapses to fit the content, rather than expand to the max-width. This only happens when auto margins are set.

Is there any way to make <main> expand to the max-width when auto-margins are set?

like image 360
Cameron Martin Avatar asked Sep 17 '14 14:09

Cameron Martin


People also ask

How do I stop my flexbox from shrinking?

Fixed size If you remove the 100% width above, then the image should retain its normal size even when the available space is reduced. However, if you want to keep the 100% img for any reason, then you need to add the flex-shrink property to the element containing the image and give it a value of 0.

How do I stop my flexbox from stretching?

By default, the child elements of a flexbox container will stretch vertically to fill the height of the container. This can be prevented by using the align-self property on the child element that you do not want to stretch.

How do I make my flexbox fixed 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.

How does margin affect flexbox?

If you apply auto margins to a flex item, that item will automatically extend its specified margin to occupy the extra space in the flex container, depending on the direction in which the auto-margin is applied.


1 Answers

Adding width: 100%; to <main> seems to fix this.

Fiddle link.

*, *:before, *:after {
    box-sizing: border-box;  
}

body {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
    margin: 0;
}

header, footer {
    background-color: #c9c9c9;
    padding: 20px;
}

main {
    flex: 1;
    margin: 0 auto;
    max-width: 300px;
    width: 100%;
    border: 1px solid red;
}
<header></header>
<main>This is some content</main>
<footer></footer>
like image 117
Cameron Martin Avatar answered Oct 10 '22 22:10

Cameron Martin