Home >Web Front-end >CSS Tutorial >Easy and Responsive Modern CSS Grid Layout

Easy and Responsive Modern CSS Grid Layout

Joseph Gordon-Levitt
Joseph Gordon-LevittOriginal
2025-02-10 10:13:10778browse

Easy and Responsive Modern CSS Grid Layout

Core points

  • CSS Grid is a powerful layout system that allows the creation of grid structures in CSS, not in HTML. Most modern browsers support it, except for IE11, which supports older versions.
  • This article demonstrates how to create a responsive modern CSS Grid layout, gradually add CSS Grid and provide fallback code for older browsers. This includes technology to center elements, span projects, and adjust the layout of small equipment.
  • CSS Grid provides utilities such as grid-column and grid-row to locate grid items, as well as properties such as justify-items, align-items and align-self to align and adjust items. It also allows nested grids, where the grid child elements themselves can be grid containers.
  • For small screen devices, you can easily change the layout structure to linearize it with CSS Grid, redefine the grid area and use media queries. This makes for a more convenient layout on smaller screens.

This article will show how to create a responsive modern CSS Grid layout, demonstrate how to use fallback code for older browsers, how to add CSS Grid step by step, and how to rebuild the layout on small devices and use alignment attribute centering elements.

In previous articles, we explored four different techniques for easily building responsive grid layouts. That post was written in 2014 — before CSS Grid was available — so in this tutorial we will use a similar HTML structure but with a modern CSS Grid layout.

In this tutorial, we will use float to create a demo with a basic layout and then enhance it with CSS Grid. We will demonstrate many useful utilities such as centering elements, spanning projects, and easily changing layouts on small devices by redefining grid areas and using media queries. You can find the code in this CodePen: CodePen link

Responsive Modern CSS Grid Layout

Before we dive into creating a responsive grid demonstration, let's first introduce CSS Grid.

CSS Grid is a powerful two-dimensional system that was added to most modern browsers in 2017. It completely changes the way we create HTML layouts. Grid layout allows us to create grid structures in CSS, not in HTML.

In addition to IE11, most modern browsers support CSS Grid. IE11 supports older versions of the standard, which may cause some problems. You can use caniuse.com to check support.

The grid layout has a parent container whose display property is set to grid or inline-grid. The child elements of the container are grid items, and they are implicitly located due to the powerful grid algorithm. You can also apply different classes to control the placement, size, position, and other aspects of the project.

Let's start with a basic HTML page. Create an HTML file and add the following:

<code class="language-html"><!DOCTYPE html>


  <title>CSS Grid Layout Example</title>
  <link rel="stylesheet" href="style.css">


  <header>
    <h2>CSS Grid Layout Example</h2>
  </header>
  <aside class="sidebar">
    <p>Sidebar</p>
  </aside>
  <main>
    <article>1</article>
    <article>2</article>
    <article>11</article>
  </main>
  <footer>
    <p>Copyright 2018</p>
  </footer>

</code>

We use HTML semantics to define the title, sidebar, body, and footer parts of a page. In the main section, we use the <article></article> tag to add a set of items. <article></article> is an HTML5 semantic tag that can be used to wrap independent and self-contained content. A single page can contain any number of <article></article> tags.

This is a screenshot of the page at this stage:

Easy and Responsive Modern CSS Grid Layout

Next, let's add the basic CSS style. Add a <style></style> tag at the head of the document and add the following style:

<code class="language-css">body {
  background: #12458c;
  margin: 0rem;
  padding: 0px;
  font-family: -apple-system, BlinkMacSystemFont,
            "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell",
            "Fira Sans", "Droid Sans", "Helvetica Neue",
            sans-serif;
}

header {
  text-transform: uppercase;
  padding-top: 1px;
  padding-bottom: 1px;
  color: #fff;
  border-style: solid;
  border-width: 2px;
}

aside {
  color: #fff;
  border-width:2px;
  border-style: solid;
  float: left;
  width: 6.3rem;
}

footer {
  color: #fff;
  border-width:2px;
  border-style: solid;
  clear: both;
}

main {
  float: right;
  width: calc(100% - 7.2rem);
  padding: 5px;
  background: hsl(240, 100%, 50%);
}

main > article {
  background: hsl(240, 100%, 50%);
  background-image: url('https://source.unsplash.com/daily');
  color: hsl(240, 0%, 100%);
  border-width: 5px;
}</code>

This is a small demo page, so we will style the tags directly for readability rather than applying the class naming system.

We use float to position the sidebar to the left, position the main body to the right, and set the width of the sidebar to a fixed 6.3rem width. Then, we calculate and set the remaining width of the body part using the CSS calc() function. The main part contains a library of projects organized into vertical blocks.

Easy and Responsive Modern CSS Grid Layout

The layout is not perfect. For example, the height of the sidebar is different from the height of the main content portion. There are various CSS techniques that can solve these problems, but most are tips or workarounds. Since this layout is a fallback for Grid, it will be seen by fewer and fewer users. The fallback is available and good enough.

The latest versions of Chrome, Firefox, Edge, Opera, and Safari all support CSS Grid, which means if your visitors use these browsers, you don't have to worry about providing fallbacks. You also need to consider Evergreen Browser. The latest versions of Chrome, Firefox, Edge and Safari are Evergreen browsers. That is, they will automatically and silently update themselves without prompting the user. To ensure your layout works properly in every browser, you can start with a floating-based default fallback and then apply modern Grid layouts using progressive enhancement techniques. Users using older browsers won't get the same experience, but that's good enough.

Progressive enhancement: You don't have to cover everything

When adding a CSS Grid layout on top of a fallback layout, you don't really have to overwrite all tags or use a completely separate CSS style:

  • In browsers that do not support CSS Grid, the grid properties you add will be simply ignored.
  • If you use float to layout elements, remember that grid items take priority over float. That is, if you add a float: left|right style to an element that is also a grid element (child of the parent element with a display: grid style), the float will be ignored and the grid is taken.
  • The @supports rules can be used to check support for specific features in CSS. This allows us to override the fallback style if necessary, while older browsers ignore the @supports block.

Now, let's add the CSS Grid to our page. First, let's mark as a grid container and set the grid columns, rows, and regions:

<code class="language-html"><!DOCTYPE html>


  <title>CSS Grid Layout Example</title>
  <link rel="stylesheet" href="style.css">


  <header>
    <h2>CSS Grid Layout Example</h2>
  </header>
  <aside class="sidebar">
    <p>Sidebar</p>
  </aside>
  <main>
    <article>1</article>
    <article>2</article>
    <article>11</article>
  </main>
  <footer>
    <p>Copyright 2018</p>
  </footer>

</code>

We use the display:grid property to mark as a grid container. We set a grid gap of 0.1vw. Gap allows you to create slots between grid cells instead of using margins. We also add two columns using grid-template-columns. The first column adopts a fixed width of 6.5 rem, and the second column adopts a residual width. fr is a fractional unit, and 1fr is equal to a part of the available space.

Next, we use grid-template-rows to add three lines. The first row uses a fixed height of 6rem, the third row uses a fixed height of 3rem, and the remaining free space (1fr) is allocated to the second row.

We then use grid-template-areas to assign the virtual cells generated by the intersection of columns and rows to the region. Now we need to use grid-area to actually define those areas specified in the area template:

<code class="language-css">body {
  background: #12458c;
  margin: 0rem;
  padding: 0px;
  font-family: -apple-system, BlinkMacSystemFont,
            "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell",
            "Fira Sans", "Droid Sans", "Helvetica Neue",
            sans-serif;
}

header {
  text-transform: uppercase;
  padding-top: 1px;
  padding-bottom: 1px;
  color: #fff;
  border-style: solid;
  border-width: 2px;
}

aside {
  color: #fff;
  border-width:2px;
  border-style: solid;
  float: left;
  width: 6.3rem;
}

footer {
  color: #fff;
  border-width:2px;
  border-style: solid;
  clear: both;
}

main {
  float: right;
  width: calc(100% - 7.2rem);
  padding: 5px;
  background: hsl(240, 100%, 50%);
}

main > article {
  background: hsl(240, 100%, 50%);
  background-image: url('https://source.unsplash.com/daily');
  color: hsl(240, 0%, 100%);
  border-width: 5px;
}</code>

Most fallback codes have no side effects on CSS Grid, except for the width of the body part width: calc(100% - 7.2rem);, which calculates the remaining width of the body part after subtracting the width of the sidebar plus any margin/filling space.

This is a screenshot of the result. Please note that the main area does not occupy all remaining width:

Easy and Responsive Modern CSS Grid Layout

To solve this problem, we can add width: auto; when supporting Grid:

<code class="language-css">body {
  /*...*/
  display: grid;
  grid-gap: 0.1vw;
  grid-template-columns: 6.5rem 1fr;
  grid-template-rows: 6rem 1fr 3rem;
  grid-template-areas: "header   header"
                       "sidebar content"
                       "footer footer";  
}</code>

This is a screenshot of the current result:

Easy and Responsive Modern CSS Grid Layout

Add nested mesh

The grid child element itself can be a grid container. Let's set the main part as a grid container:

<code class="language-html"><!DOCTYPE html>


  <title>CSS Grid Layout Example</title>
  <link rel="stylesheet" href="style.css">


  <header>
    <h2>CSS Grid Layout Example</h2>
  </header>
  <aside class="sidebar">
    <p>Sidebar</p>
  </aside>
  <main>
    <article>1</article>
    <article>2</article>
    <article>11</article>
  </main>
  <footer>
    <p>Copyright 2018</p>
  </footer>

</code>

We use a grid gap of 0.1vw and use the repeat(auto-fill, minmax(12rem, 1fr)); function to define columns and rows. The auto-fill option tries to fill the free space with as many columns or rows as possible, and creates an implicit column or row if needed. If you want to put available columns or rows into the available space, you need to use auto-fit. Read a good explanation about the difference between auto-fill and auto-fit.

This is a screenshot of the result:

Easy and Responsive Modern CSS Grid Layout

Use Grid grid-column, grid-row and span keywords

CSS Grid provides grid-column and grid-row, which allow you to locate grid items within the parent grid using grid lines. They are abbreviation for the following properties:

  • grid-row-start: Specify the starting position of the grid item in the grid row
  • grid-row-end: Specify the end position of the grid item in the grid row
  • grid-column-start: Specify the starting position of the grid item in the grid column
  • grid-column-end: Specify the end position of the grid item in the grid column

You can also use the span keyword to specify how many columns or rows to span.

Let's make the second child element of the main area span four columns and two rows and position it from the second column and first row (which is also its default position):

<code class="language-css">body {
  background: #12458c;
  margin: 0rem;
  padding: 0px;
  font-family: -apple-system, BlinkMacSystemFont,
            "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell",
            "Fira Sans", "Droid Sans", "Helvetica Neue",
            sans-serif;
}

header {
  text-transform: uppercase;
  padding-top: 1px;
  padding-bottom: 1px;
  color: #fff;
  border-style: solid;
  border-width: 2px;
}

aside {
  color: #fff;
  border-width:2px;
  border-style: solid;
  float: left;
  width: 6.3rem;
}

footer {
  color: #fff;
  border-width:2px;
  border-style: solid;
  clear: both;
}

main {
  float: right;
  width: calc(100% - 7.2rem);
  padding: 5px;
  background: hsl(240, 100%, 50%);
}

main > article {
  background: hsl(240, 100%, 50%);
  background-image: url('https://source.unsplash.com/daily');
  color: hsl(240, 0%, 100%);
  border-width: 5px;
}</code>

This is a screenshot of the result:

Easy and Responsive Modern CSS Grid Layout

Using the Grid Alignment Utility

We want to center the text in the title, sidebar and footer, and the numbers in the <article></article> element.

CSS Grid provides six properties justify-items, align-items, justify-content, align-content, justify-self, align-self,

, and

that can be used to align and adjust grid items. They are actually part of the CSS box alignment module. header asideAdd the following in the article, footer,

and
<code class="language-css">body {
  /*...*/
  display: grid;
  grid-gap: 0.1vw;
  grid-template-columns: 6.5rem 1fr;
  grid-template-rows: 6rem 1fr 3rem;
  grid-template-areas: "header   header"
                       "sidebar content"
                       "footer footer";  
}</code>
selectors:
  • justify-items
  • Used to adjust grid items along the row axis or horizontal direction. align-items startend Align the grid items along the column axis or vertical direction. They can all take center, stretch,
  • , and
values.

This is a screenshot after the centering element: Easy and Responsive Modern CSS Grid Layout

Rebuild the grid layout in small devices

Our demo layout is convenient for medium and large screens, but may not be the best way to build a page for small screen devices. With CSS Grid, we can easily change this layout structure to linearize it in small devices—by redefining the grid area and using media queries.

Here is a screenshot before adding the code to rebuild the layout on a small device:

Easy and Responsive Modern CSS Grid Layout

Now, add the following CSS code:

<code class="language-html"><!DOCTYPE html>


  <title>CSS Grid Layout Example</title>
  <link rel="stylesheet" href="style.css">


  <header>
    <h2>CSS Grid Layout Example</h2>
  </header>
  <aside class="sidebar">
    <p>Sidebar</p>
  </aside>
  <main>
    <article>1</article>
    <article>2</article>
    <article>11</article>
  </main>
  <footer>
    <p>Copyright 2018</p>
  </footer>

</code>

On devices with widths less than 575 pixels, the layout becomes linear:

Easy and Responsive Modern CSS Grid Layout

Note that the width of the sidebar does not fill the available width. This is caused by the fallback code, so all we need to do is to use width: auto; override width: 6.3rem; on Grid-enabled browsers

<code class="language-css">body {
  background: #12458c;
  margin: 0rem;
  padding: 0px;
  font-family: -apple-system, BlinkMacSystemFont,
            "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell",
            "Fira Sans", "Droid Sans", "Helvetica Neue",
            sans-serif;
}

header {
  text-transform: uppercase;
  padding-top: 1px;
  padding-bottom: 1px;
  color: #fff;
  border-style: solid;
  border-width: 2px;
}

aside {
  color: #fff;
  border-width:2px;
  border-style: solid;
  float: left;
  width: 6.3rem;
}

footer {
  color: #fff;
  border-width:2px;
  border-style: solid;
  clear: both;
}

main {
  float: right;
  width: calc(100% - 7.2rem);
  padding: 5px;
  background: hsl(240, 100%, 50%);
}

main > article {
  background: hsl(240, 100%, 50%);
  background-image: url('https://source.unsplash.com/daily');
  color: hsl(240, 0%, 100%);
  border-width: 5px;
}</code>
This is a screenshot of the final result:

Easy and Responsive Modern CSS Grid Layout

You can find the final code in the CodePen displayed at the beginning of this article, or directly access CodePen:

CodePen link

Conclusion

In this tutorial, we created a responsive demo layout using CSS Grid. We demonstrate using fallback code for older browsers, step-by-step adding CSS Grid, rebuilding the layout in small devices, and using alignment attribute centering elements.

FAQs about easy and responsive modern CSS Grid layouts

What is the difference between CSS Grid and Flexbox?

CSS Grid and Flexbox are both powerful layout systems in CSS. While they can be used interchangeably in some cases, they each have their own unique advantages. Flexbox is a one-dimensional layout model that is especially suitable for assigning items along columns or rows. CSS Grid, on the other hand, is a two-dimensional layout system that is ideal for arranging elements in rows and columns at the same time. It is perfect for creating complex web layouts.

How to make my CSS Grid layout responsive?

CSS Grid makes it easy to create responsive layouts without media queries. You can use

units, which represent a portion of the available space in the grid container. For example, if you want three columns of monospace, you can use fr. The column will automatically resize to fit the screen. grid-template-columns: 1fr 1fr 1fr

Can I use CSS Grid and Flexbox together?

Yes, CSS Grid and Flexbox can be used together for layouts. You can use CSS Grid to create an overall page layout and then use Flexbox to layout individual components or parts within a grid cell. This combination allows for a high degree of flexibility and control over the layout.

How to align items in CSS Grid?

CSS Grid provides several properties for aligning items, including justify-items, align-items, justify-self, and align-self. These properties can be used to align items along row axis (align) or column axis (align). For example, justify-items: center will center the item along the line axis.

How to create gaps between grid projects?

You can use the grid-gap property to create gaps between grid items. This property is the abbreviation for grid-row-gap and grid-column-gap. For example, grid-gap: 20px will create a 20px gap between all grid items.

How do the

auto-fill and auto-fit keywords work in CSS Grid?

The

auto-fill and auto-fit keywords are used with the grid-template-columns functions in the grid-template-rows and repeat() properties. auto-fill Use as many items as possible to fill rows or columns, and create empty cells if there are insufficient items. auto-fit behaves similarly, but it collapses empty cells, making the item stretch to fill the row or column.

How to overlap items in CSS Grid?

In CSS Grid, you can overlap items by placing items on the same grid cell or having them span multiple cells. You can use the z-index attribute to control the stacking order of overlapping items.

Can I use CSS Grid in all my browsers?

CSS Grid is supported by all modern browsers such as Chrome, Firefox, Safari, and Edge. However, Internet Explorer does not support it. If you need to support Internet Explorer, you may need to use a fallback layout.

How to create nested grids in CSS Grid?

You can create nested meshes by setting the mesh item itself as a mesh container. Just apply display: grid to your grid project and define the grid layout like you would for any grid container.

How to control the size of grid tracks in CSS Grid?

You can use the grid-template-rows and grid-template-columns properties to control the size of the grid track (rows and columns). You can specify sizes using various units, such as pixels (px), percentages (%), or fractions (fr).

Please note that the above content has greatly rewritten and polished the original text, striving to make the article smoother, easier to read, and more in line with the writing style of modern online articles without changing the original meaning. The image format remains the same. The CodePen link is not available due to inability to access external websites and files. Please replace it yourself.

The above is the detailed content of Easy and Responsive Modern CSS Grid Layout. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn