search
HomeWeb Front-endCSS Tutorial4 CSS Grid Properties (and One Value) for Most of Your Layout Needs

4 CSS Grid Properties (and One Value) for Most of Your Layout Needs

CSS Grid gives us a powerful website layout system. The CSS-Tricks guide provides a comprehensive overview of Grid's properties and layout examples. We will take the opposite approach, showing you the minimum set of Grid attributes required to meet most layout requirements.

These five attributes will help you get started quickly:

  • display (for grid value)
  • grid-template-columns
  • grid-gap
  • grid-auto-flow
  • grid-column / grid-row

Here is its simplicity. Suppose you want to implement the following layout for small, medium and large screens.

Here is the markup we will use:

<nav><ul>
<li>
<li>
<li>
<li>
<li>
<li>
<li>
<li>
<li>
</ul></nav><div></div>

If we apply some baseline style, we will get the following results, which is enough for small screens:

Now we can get a deeper understanding of the Grid properties!

Use display: grid to divide the page into independent layout containers

First, we need to determine which parts of the page should align with the Grid layout. A single Grid layout can be defined for the entire page. However, for websites with very complex structures (such as news sites), handling large Grids can quickly become uncontrollable. In this case, I recommend breaking it down into several independent Grid containers.

Like this:

Where do you draw the boundary between what is a Grid and what is not a Grid? Here is a personal rule of thumb I followed:

If the layout of a specific part of the page does not fit the Grid of adjacent or surrounding page parts, then set that part as its own Grid container.

I've drawn the Grid line in the section of the page with .container-main class as shown in the following image. You may notice that the part of .container-inner class from the tag does not exactly fit the Grid of the row.

This is another possible layout, if a finer line grid is chosen, a small portion fits around the Grid. No separate Grid container is needed here.

First, let's convert .container-main to a Grid container. Here is the basic building block of CSS Grid - converting elements into Grid containers using display attribute:

 .container-main {
  display: grid;
}

We also need to do the same for other Grid containers:

 .container-inner {
  display: grid;
}

.container-nav {
  display: grid;
}

Use grid-template-columns to define the required column

Next, we will define the number of columns required in each Grid container and the width of those columns. My guideline on the number of columns: Use the minimum common multiple of the maximum number of columns required for different screen sizes.

How does this work? .container-main element has two columns on a medium-sized screen. If we multiply this by the number of columns on a large screen (three columns), we will get a total of six columns.

We can also do the same for navigation ( .container-inner element). There are three columns on the medium size screen, and we multiply this by one on the large screen and we get a total of three columns.

.container-nav element has no column number. In this case, the Grid system should automatically adjust the number of columns to the number of menu elements. It is common to add or delete items in the navigation, and it would be great if it responds accordingly, which is what Grid can help us implement later.

OK, so we define the number of columns for each Grid container. Let's set them in place using grid-template-columns property. But first, there are some details:

  • grid-template-columns attribute is only used in Grid containers. In other words, you won't find it on the Grid project inside the container (at least correctly).
  • This property accepts many different values ​​that define both the number of columns and the width of the column. What we are interested here is the fraction (fr) units. I highly recommend you check out Robin's overview because it's unique to Grid and does a great job of calculating how to put Grid elements into Grid containers.

We need to use six monospace columns in .container-main . We can write this way:

 .container-main {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr;
}

Alternatively, we can use the repeat() function to simplify it to something more readable:

 .container-main {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
}

Let's use this knowledge to apply it to our .container-inner element as well, and we decide it needs three columns.

 .container-inner {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}

Add spacing between Grid projects using grid-gap

By default, Grid uses all its space in the Grid container to house Grid projects. Keeping elements close together may be a design requirement, but it is not the case for the specific layout we are making. We want some breathing space between things!

For this we have grid-gap attribute. Again, this is a property that only works with Grid containers, all it does is create vertical and horizontal spacing between Grid projects. It is actually an abbreviation property that combines the vertical spacing function of grid-row-gap and the horizontal spacing function of grid-column-gap . Conveniently, we can break them down like that, but in this case we use the same amount of spacing in each direction, the abbreviation grid-gap is easier to write.

We want to have a 20px spacing between Grid projects in .container-main , 10px spacing in .container-inner , and 5px spacing in .container-nav . no problem! Each Grid container requires only one line of code.

 .container-main{
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  grid-gap: 20px;
}

.container-inner {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 10px;
}

.container-nav {
  display: grid;
  grid-gap: 5px;
}

Use grid-column and grid-row to determine the size of each Grid project

Now it’s time to turn the layout into what we want it to be!

First is grid-column property, which allows us to extend the Grid project to n columns, where n is the number of columns to be spanned. If you think this sounds very much like the rowspan property in an HTML table that allows us to extend the cell across multiple rows, you can't be wrong.

When we use it on the Grid .item in .container-main element and on .item-inner element in .container-inner , it looks like this:

 .item {
  grid-column: span 6;
}

.item-inner {
  grid-column: span 3;
}

What we are talking about here is that each item spans six rows in our main container and three rows in our internal container – this is the total number of columns in each container.

One interesting thing about CSS Grid is that we can name the lines of Grid. They come with implicit names out of the box, but naming them is an effective way to distinguish between the start and end lines of each column on the track.

We can change the number of columns and rows that the project should span at different breakpoints:

 @media screen and (min-width: 600px) {
  .item-type-b {
    grid-column: span 3;
  }

  .item-inner {
    grid-column: span 1;
  }
}

@media screen and (min-width: 900px) {
  .item {
    grid-column: span 2;
    grid-row: span 2;
  }

  .item-type-b{
    grid-row: span 1;
  }

  .item-inner{
    grid-column: span 3;
  }
}

Use grid-auto-flow to control the placement of elements

CSS Grid places elements one by one in the row. This is why the result in our example currently looks like this:

Column-by-column placement can be achieved by setting grid-auto-flow property to column ( row is the default). Our layout will benefit from columnar placement in both cases. First, it makes our menu items eventually appear horizontally. Second, it brings elements of the container class into the desired combination.

Final result

Conclusion: More or less norms?

The Grid system allows us to work under the motto, “do as many specifications as needed, but as few as possible”. To illustrate how much you only need to know to build or even complex layouts with CSS Grid, we've only covered some specifications needed to convert elements to CSS Grid containers and to convert the items in them to Grid projects.

CSS Grid supports the following additional use cases:

  • We want to develop fewer specifications to rely more on automatic positioning.
  • We want to develop more specifications to determine more details of the layout of the results.

If the first case applies, it is worth considering the following other Grid options:

  • When creating a Grid using grid-template-columns , you can use the auto keyword to let the Grid system automatically determine the width of each column, or adjust it to existing content using min-content , max-content or fit-content settings.
  • You can use repeat , auto-fill , auto-fit and minmax to let the Grid system automatically determine the number of columns required. Even media queries can become redundant, and these tools help increase flexibility without adding more media queries.

Here are some articles I recommend on this topic: Become a CSS Grid Ninja! and auto-resize columns in CSS Grid: auto-fill with auto-fit .

If the second case applies, CSS Grid provides you with more settings options:

  • You can explicitly specify the width of the column using the unit of your choice (such as px or %), using grid-template-columns property. Additionally, grid-template-rows property can be used to define the number and width of rows if there is a specific number of rows.
  • You can also define a specific column or line number as the values ​​of grid-column and grid-row (or use grid-column-start , grid-column-end , grid-row-start or grid-row-end properties).

We haven't even involved CSS Grid alignment yet! Still, we can do so much without discussing the topic, which shows how powerful the CSS Grid is.

The above is the detailed content of 4 CSS Grid Properties (and One Value) for Most of Your Layout Needs. 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
Simulating Mouse MovementSimulating Mouse MovementApr 22, 2025 am 11:45 AM

If you've ever had to display an interactive animation during a live talk or a class, then you may know that it's not always easy to interact with your slides

Powering Search With Astro Actions and Fuse.jsPowering Search With Astro Actions and Fuse.jsApr 22, 2025 am 11:41 AM

With Astro, we can generate most of our site during our build, but have a small bit of server-side code that can handle search functionality using something like Fuse.js. In this demo, we’ll use Fuse to search through a set of personal “bookmarks” th

Undefined: The Third Boolean ValueUndefined: The Third Boolean ValueApr 22, 2025 am 11:38 AM

I wanted to implement a notification message in one of my projects, similar to what you’d see in Google Docs while a document is saving. In other words, a

In Defense of the Ternary StatementIn Defense of the Ternary StatementApr 22, 2025 am 11:25 AM

Some months ago I was on Hacker News (as one does) and I ran across a (now deleted) article about not using if statements. If you’re new to this idea (like I

Using the Web Speech API for Multilingual TranslationsUsing the Web Speech API for Multilingual TranslationsApr 22, 2025 am 11:23 AM

Since the early days of science fiction, we have fantasized about machines that talk to us. Today it is commonplace. Even so, the technology for making

Jetpack Gutenberg BlocksJetpack Gutenberg BlocksApr 22, 2025 am 11:20 AM

I remember when Gutenberg was released into core, because I was at WordCamp US that day. A number of months have gone by now, so I imagine more and more of us

Creating a Reusable Pagination Component in VueCreating a Reusable Pagination Component in VueApr 22, 2025 am 11:17 AM

The idea behind most of web applications is to fetch data from the database and present it to the user in the best possible way. When we deal with data there

Using 'box shadows' and clip-path togetherUsing 'box shadows' and clip-path togetherApr 22, 2025 am 11:13 AM

Let's do a little step-by-step of a situation where you can't quite do what seems to make sense, but you can still get it done with CSS trickery. In this

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.