I need to center a set of children in a container.
My requirements are:
- Each child needs a gutter to its left and right.
- I cannot set a margin or padding on the container.
- I cannot set padding on the children, but I can set margins.
- Each child should have a space/gutter to its left and right.
- Each child can have a different max-width set.
- If the child's max-width is greater than the container width, it should take up the full width (minus its gutters).
- If the child is narrower than the container it should be centered.
I thought I would be able to achieve this with flexbox, because
align-items: stretch;
respects max-widths, however it will not center the children.
I cannot use margin: 0 auto;
because I need to use the childrens' margins to set up the gutters to their left and right.
Here is my attempt using flexbox:
* {
box-sizing: border-box;
}
main {
display: flex;
flex-direction: column;
align-items: stretch;
text-align: center;
max-width: 600px;
outline: 1px dashed black;
box-
}
section {
min-height: 40px;
margin-left: 20px;
margin-right: 20px;
}
section + section {
margin-top: 20px;
}
.s1 {
background-color: red;
max-width: 100px
}
.s2 {
background-color: blue;
max-width: 200px
}
.s3 {
background-color: green;
max-width: 300px
}
<main>
<section class='s1'></section>
<section class='s2'></section>
<section class='s3'></section>
</main>
Is there any way to reliably achieve what I'm after?