Loading course content...
Loading course content...
Code Playground is only enabled on larger screen sizes.
All three layout methods we just discussed are widely used in real life, even the legacy method, which is still supported by many popular CSS frameworks.
However, you may have noticed that it doesn't matter if you are using flexbox, grid, or the grid view. You will need to use media queries to create breakpoints for different devices.
Today, electronic devices come in many different sizes. In our example, we only created two breakpoints for medium and large devices, but in reality, you probably need many more breakpoints than that.
So, is it possible for us to simplify this process and create responsive layouts without using media queries?
The answer is yes, but it does require some smart programming.
Say you are creating a webpage showing a list of articles using card components like this:

<h1>List of articles</h1>
<div class="cards">
<div class="card">
<h2>Lorem ipsum dolor sit amet</h2>
<p>Sapiente eligendi nam . . .</p>
</div>
<!-- . . . -->
</div>First of all, let's think about how to create this list using grids.
Assume each card is 20em wide, then you can automatically create the grid template using the repeat() function:
.card {
border: 2px solid black;
border-radius: 5px;
padding: 10px;
}
.cards {
display: grid;
grid-template-columns: repeat(auto-fill, 20em);
grid-gap: 1em;
}The repeat() function creates a list of items based on the given values, which has the following syntax:
repeat(<number_of_columns>, <column_size>)In this example, the column size is 20em, and the number of columns is set to auto-fill, which means the browser will automatically find the maximum number of columns required to fill the entire row.

With this setup, you no longer need to use media queries, and the browser will automatically change the number of columns based on the viewport size.
However, this solution has one issue. Notice that when the viewport is not wide enough to fill an extra card, a very noticeable blank space will be left on the page.
In this case, you should ensure that individual card also adapts as the viewport widens, instead of being fixed to 20em.
This can be achieved using the minmax() function.
.cards {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(20em, 1fr));
grid-gap: 1em;
}The minmax() function gives a size that is greater than min(20em), and smaller than max(1fr) in order to fill the empty space.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="/styles.css"> </head> <body> <div class="container"> <div class="nav">Navbar</div> <div class="side-primary">Primary sidebar</div> <div class="content"> Main Content <p>. . .</p> </div> <div class="side-secondary">Secondary sidebar</div> <div class="footer">Footer</div> </div> </body> </html>