Problem
I am currently trying to left-align blocks within a centered wrapper with dynamic width. I can't get this to work using only HTML/CSS.
Here is a JSFiddle: https://jsfiddle.net/hudxtL8L/
Examples
So currently, it looks like this:
| _____ _____ |
| | | | | |
| | | | | |
| |_____| |_____| |
| _____ _____ |
| | | | | |
| | | | | |
| |_____| |_____| |
| _____ |
| | | |
| | | |
| |_____| |
| |
And I want it to look like this:
| _____ _____ |
| | | | | |
| | | | | |
| |_____| |_____| |
| _____ _____ |
| | | | | |
| | | | | |
| |_____| |_____| |
| _____ |
| | | |
| | | |
| |_____| |
| |
or, on a bigger device, something like this:
| _____ _____ _____ |
| | | | | | | |
| | | | | | | |
| |_____| |_____| |_____| |
| _____ _____ _____ |
| | | | | | | |
| | | | | | | |
| |_____| |_____| |_____| |
| _____ |
| | | |
| | | |
| |_____| |
| |
The important thing here is that the last row is not centered, but left-aligned within the centered parent. Can this be done, and if so, how? I tried different approaches but all of them failed.
Tried approaches
margin: 0 auto will not work since it requires a fixed width, but I want as many .element
's as possible per row.
Using a table seems difficult as well, since I don't know how many .element
's will fit in one row on the current device.
Using javascript will of course work, but I have the feeling that there is a CSS-only solution to this.
Use can use CVS flex
to realize this layout.
One approach is to define a container, #content
that has a fixed width and center it with margin: 0 auto
.
Apply the flex properties to #content
, use justify-content: space-between
to get the child elements in the desired positions.
The child .elements
need flex-basis: 100px
to specify the width within the flex
container context.
You can control the spacing between elements using margins.
Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout
#viewport {
border: 1px solid black;
}
#content {
width: 250px;
margin: 0 auto;
border: 1px dashed blue;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
.element {
border: 1px dotted black;
flex-basis: 100px;
height: 100px;
margin: 10px; /* optinal, gives you some control on spacing */
}
<div id="viewport">
<div id="content">
<div class="element">1</div>
<div class="element">2</div>
<div class="element">3</div>
<div class="element">4</div>
<div class="element">5</div>
</div>
</div>