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?
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.
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With