Building custom responsive layouts is always exciting. This article examines a technique that we can use to take full control of the distance between grid columns. To demonstrate this, I’ll use the example of a responsive image gallery.
Building a Responsive Layout
To begin with, let’s assume on large screens our gallery should look something like this:
On smaller screens (i.e. <50em), it should have the following appearance:
The markup is simple:
[code language="html"]
<div>
<a href="path-to-the-image">
<figure>
<img src="path-to-the-image" alt="">
</figure>
</a>
<!-- other anchors here ... -->
</div>
[/code]
As you probably already know, we can take advantage of different layout methods for generating the desired result. Before I examine two of those possible methods, let’s take note of our initial requirements (see previous visualizations):
- I want a 2-column layout on medium screens and smaller (i.e. <50em), and a 4-column layout on large screens (50em or above).
- The distance between columns should be 8px.
Using inline-block
I’ll first use the display:inline-block
method to build our gallery. Consider the following CSS:
[code language="css"]
div {
font-size: 0;
}
a {
font-size: 16px;
display: inline-block;
margin-bottom: 8px;
width: calc(50% - 4px);
margin-right: 8px;
}
a:nth-of-type(2n) {
margin-right: 0;
}
@media screen and (min-width: 50em) {
a {
width: calc(25% - 6px);
}
a:nth-of-type(2n) {
margin-right: 8px;
}
a:nth-of-type(4n) {
margin-right: 0;
}
}
[/code]
Here’s an explanation of what I’ve done:
By default, there’s a space between inline-block
elements. One way to override this is to set the font size of the parent element to zero. This might also require that we reset the font size of any child elements (not necessary in our case).
On small screens I have a 2-column layout and I specify 8px of space between columns.
The width of our columns is calculated as follows:
- Total space between columns per row = 1 * 8px => 8px. The derived value is 8px and not 16px because I remove the right margin for every second column on small screens.
- The width of each column = calc(50% - 4px). The value 4px derived by calculating: Total space between columns per row / Number of columns per row (8px / 2 => 4px).
On large screens I have a 4-column layout and I specify 8px space between columns. So, the width of our columns is calculated as follows:
Continue reading %Using Modern CSS to Build a Responsive Image Grid%
by George Martsoukos via SitePoint
No comments:
Post a Comment