DEV Community

Per for Scrimba

Posted on • Updated on • Originally published at freecodecamp.org

How to make your HTML responsive by adding a single line of CSS

Photo by [TJ Holowaychuk](https://medium.com/u/bbb3c7ccb0a0)(https://medium.com/u/bbb3c7ccb0a0)Photo by TJ Holowaychuk

In this article, I’ll teach you how to use CSS Grid to create a super cool image grid which varies the number of columns with the width of the screen.

And the most beautiful part: the responsiveness will be added with a single line of CSS.

This means we don’t have to clutter up the HTML with ugly class names (i.e. col-sm-4, col-md-8) or create media queries for every single screen size.

I’ve also created a free CSS Grid course. Click here to get full access to it.

Click the image to get to the courseClick the image to get to the course.

Now let’s jump into it!

The setup

For this article, we’ll continue on with the grid we used in my first CSS Grid article. Then we’ll add the images at the end of the article. Here’s how our initial grid looks:

Here’s the HTML:

<div class="container">  
  <div>1</div>  
  <div>2</div>  
  <div>3</div>  
  <div>4</div>  
  <div>5</div>  
  <div>6</div>  
</div>
Enter fullscreen mode Exit fullscreen mode

And the CSS:

.container {  
    display: grid;  
    grid-template-columns: 100px 100px 100px;  
    grid-template-rows: 50px 50px;  
}
Enter fullscreen mode Exit fullscreen mode

Note: the example also has a little bit of basic styling, which I won’t go into here, as it’s got nothing to do with CSS Grid.

If this code confuses you, I’d recommend you to read my Learn CSS Grid in 5 minutes article, where I explain the basics of the layout module.

Let’s start by making the columns responsive.

Basic responsiveness with the fraction unit

CSS Grid brings with it a whole new value called a fraction unit. The fraction unit is written like fr, and it allows you to split the container into as many fractions as you want.

Let’s change each of the columns to be one fraction unit wide.

.container {  
    display: grid;  
    grid-template-columns: 1fr 1fr 1fr;  
    grid-template-rows: 50px 50px;  
}
Enter fullscreen mode Exit fullscreen mode

What happens here is that the grid splits the entire width into three fractions and each of the columns take up one unit each. Here is the result:

If we change the grid-template-columns value to1fr 2fr 1fr, the second column will now be twice as wide as the two other columns. The total width is now four fraction units, and the second one takes up two of them, while the others take up one each. Here’s how that looks:

In other words, the fraction unit value makes it super easy for you to change the width of the columns.

Advanced responsiveness

However, the example above doesn’t give us the responsiveness we want, as this grid will always be three columns wide. We want our grid to vary the number of columns with the width of the container. To achieve that, you’ll have to learn three new concepts.

repeat()

We’ll start with the repeat() function. This is a more powerful way of specifying your columns and rows. Let’s take our original grid and change it to using repeat():

.container {  
    display: grid;  
    grid-template-columns: repeat(3, 100px);  
    grid-template-rows: repeat(2, 50px);  
}
Enter fullscreen mode Exit fullscreen mode

In other words, repeat(3, 100px) is identical to 100px 100px 100px. The first parameter specified how many columns or rows you want, and the second specifies their width, so this will just give us the exact same layout as we started out with:

auto-fit

Then there’s auto-fit. Let’s skip having a fixed amount of columns, and rather replace 3 with auto-fit.

.container {  
    display: grid;  
    grid-gap: 5px;  
    grid-template-columns: repeat(auto-fit, 100px);
    grid-template-rows: repeat(2, 100px);  
}
Enter fullscreen mode Exit fullscreen mode

This results in the following behaviour:

The grid now varies the number of columns with the width of the container.

It simply tries to fit as many 100px wide columns into the container as possible.

However, if we hard code all columns to be exactly 100px, we’ll never get the flexibility we want, as they’ll rarely add up to the full width. As you can see on the gif above, the grid often leaves white space on the right-hand side.

minmax()

The final ingredient we need in order to fix this is called minmax(). We’ll simply replace 100px with minmax(100px, 1fr). Here’s the final CSS.

.container {  
    display: grid;  
    grid-gap: 5px;  
    grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
    grid-template-rows: repeat(2, 100px);  
}
Enter fullscreen mode Exit fullscreen mode

Notice that all the responsiveness happens in a single line of CSS.

This results in the following behaviour:

And as you can see that works perfectly. The minmax() function defines a size range greater than or equal to min and less than or equal to max.

So the columns will now always be at least 100px. However, if there is more available space, the grid will simply distribute this equally to each of the columns, as the columns turn into a fraction unit instead of 100 px.

Adding the images

Now the final step is to add the images. This has nothing to do with CSS Grid, but let’s still look at the code.

We’ll start off by adding an image tag inside of each of the grid items.

<div><img src="img/forest.jpg"/></div>
Enter fullscreen mode Exit fullscreen mode

To make the image fit into the item, we’ll set it to be as wide and tall as the item itself, and then use object-fit: cover;. This will make the image cover its entire container, and the browser will crop it if it’s needed.

.container > div > img {  
    width: 100%;  
    height: 100%;  
    object-fit: cover;  
}
Enter fullscreen mode Exit fullscreen mode

Which ends up like the following:

And that’s it! You now know one of the most complex concepts in CSS Grid, so give yourself a pat on the back.

Browser support

Before we end, I also need to mention browser support. At the time of writing this article, 92% of global website traffic supports CSS Grid.

I believe CSS Grid is a must-have skill for front-end developers going forward. Much like what has happened with CSS Flexbox in the last couple of years.

So check out my CSS Grid course if you're interested in learning the subject properly.

Thanks for reading! My name is Per, I’m the co-founder of Scrimba, a tool for creating interactive coding screencasts. Follow me on Twitter and Instagram if you want to keep in touch.

Top comments (40)

Collapse
 
viccw profile image
Vic Seedoubleyew

Thanks for this article, it is very interesting.

Just one comment: I find it a pity that its title is misleading. As it is now, it sounds as though one could make one's whole website responsive with just one line of CSS. That isn't what this article aims at explaining: it explains how to make a grid responsive with just one line of CSS. This is already really interesting, so no need to oversell.

Collapse
 
klamping profile image
Kevin Lamping

Even just changing HTML -> Grid makes a huge difference in the title. "How to make your Grid responsive by adding a single line of CSS" would be so much better.

Collapse
 
viktorvillalobos profile image
Víctor Villalobos

Great article, great examples. What do you use for the animations???

Collapse
 
louislow profile image
Louis Low • Edited

I can probably create a single line responsive to HTML targeting specific element with Yogurt such as:

Using Fluid utility module: set the margin, padding, and font size adaptively adjust with different screen width.

<!-- example in HTML -->
<y class="fluid m-min-lg m-max-sm p-min-sm p-max-lg text-min-lg text-min-md">
  ...
</y>
// example in CSS
body {
  @extend .fluid, .m-min-lg, .m-max-sm, .p-min-sm, .p-max-lg .text-min-lg, .text-min-md;
}

Or using a native responsive variant utility: on the mobile screen an element width is max, the tablet screen is max, the laptop screen is small, the desktop screen is extra small.

<!-- example in HTML -->
<y class="sm:max-w-full md:max-w-full lg:max-w-sm 2k:max-w-xs">
  ...
</y>
// example in CSS
body {
  @extend .sm:\max-w-full, .md:\max-w-full, .lg:\max-w-sm, .\32k:\max-w-x;
}
Collapse
 
strezag profile image
Gabriel Streza

Repost from 2017?

Collapse
 
matthe521 profile image
Matt-He • Edited

I rarely use CSS control for responsive devices. I just add a line of code directly to the page.(can't appear the code below...just meta name="viewport"...code )

It's easy to implement responsive devices. Such as this effect: pngix.com/viewpng/ohhbJw_responsiv...

Collapse
 
mchungaji profile image
Martin Kiogora

This is so encouraging for a beginner like me. I've been very lazy with my Web Development journey but after a long lazy break I'm back again. Finished basic HTML stuff last night and was looking for CSS motivation and your post encouraged me some more. Just wondering what total beginner stuff or tutorial would you recommend? Would appreciate much any suggestions. Thank you for sharing this.

Collapse
 
craftyminer1971 profile image
CraftyMiner1971

Who knew, beside you and now the rest of the world, that you could have such responsive grids with such a simple piece of CSS! Thanks, Per, that's great!

Collapse
 
tamasviktor profile image
@tamasviktor

Awesome!

Collapse
 
omhax profile image
Om Hax

Thank you for the tutorial. It's help me a lot.

Collapse
 
ganar profile image
Gabriel N

This may work on a browser, but have you consider the current support of Grid CSS among the mail clients? Outlook is still very much in use and has a ton of limitations.

Collapse
 
csirolli profile image
Christian Sirolli

Sounds like a Microsoft problem.

Collapse
 
ganar profile image
Gabriel N

This is a problem that has to be endured by the users, not Microsoft. It may not look as much but there are still large holdouts in certain industries where applying this formula does not work: Health, Banking and Finance, Mining among others.
The author made a primer on CSS Grid, but do be aware that much work has to be done to make this work in legacy browsers and email clients.