Without-a-doubt layout in any modern website or application is one of the most challenging parts, especially when you want it to work on both desktop and small handheld devices like iPhone’s.
For a project I am working on, I have been extensively using Flexbox for the layout where applicable. One such layout is a grid of blog posts at the bottom of each page for clickthrough.
These items have varied length post titles and imagery. It only takes one title to be shorter than the others and float:left
and display:inline-block
solutions fall apart.
The kind of layout I am dealing with is a maximum of 4 items. When screen size permits, all 4 items are shown. As the screen size gets smaller, columns are dropped. 4, then 3, then 2 and finally 1.
One other constraint was the first and last items for smaller displays were to rest against the side of the container (with no space added). Only the middle items would have gutters.
The final solution I ended up coming up with was:
/* Wraps all blocks */
.blocks {
display: flex;
flex-wrap: wrap; /* Items drop below if they exceed width limitations */
}
.blocks__block {
background: #FFF;
display: flex;
overflow: hidden;
width: 100%;
}
.blocks__block__inner {
display: flex;
flex: 1 0 auto; /* Grow inner content to make grid items all same size */
flex-direction: column;
margin: 0 0 15px 0;
width: 100%;
}
@media all and (min-width: 40em) {
.blocks__block {
width: 50%;
}
.blocks__block:nth-of-type(2) .blocks__block__inner,
.blocks__block:nth-of-type(4) .blocks__block__inner {
margin-left: 15px;
}
}
@media all and (min-width: 60em) {
.blocks__block {
width: 25%;
}
.blocks__block:first-child .blocks__block__inner { margin-left: 0; }
.blocks__block:last-child .blocks__block__inner { margin-right: 0; }
.blocks__block__inner {
margin: 0 15px;
}
}
I realise this isn’t the prettiest of code, but my needs more sort of specific so I could use nth-of-type to ensure the second and fourth items in my grid of 4 items were overridden when going to the two column layout.
Please feel free to use the above code in your projects, hopefully this helps you out as much as it helped me out. Also, remember to run the code through Autoprefixer or equivelent to get browser prefixes depending on browsers you support.
The way i always tend to deal with this is having something like:
“`
.blocks {
margin-right: -10px;
margin-left: -10px;
}
.blocks__block {
flex: 1;
margin-right: 10px;
margin-right: 10px;
}
“`
This means i can use as many as i like without any `:nth-child`based stuff.
Also if you need fixed width children you can do:
“`
.blocks__block {
width: calc(25% – 20px);
margin-right: 10px;
margin-left: 10px;
“`