CSS Grid, the comprehensive guide offered by conduct.edu.vn, represents a pivotal shift in web design, offering unparalleled control over user interface layouts. As a two-dimensional grid-based layout system, it surpasses previous methods, enabling designers to craft intricate designs with ease. This guide dives deep into every facet of CSS Grid, from its fundamental concepts to advanced techniques, ensuring you’re well-equipped to create responsive and visually appealing web layouts. Explore the power of grid arrangement, track sizing, and flexible units to revolutionize your approach to web design.
1. Understanding the Essentials of CSS Grid
CSS Grid Layout, frequently called “Grid” or “CSS Grid,” denotes a paradigm shift in how we structure user interfaces on the web. Different from any prior web layout framework, Grid provides a two-dimensional grid-based structure that fundamentally alters our approach to web page design. In the past, CSS has been the principal tool for structuring web pages; however, its capabilities have been somewhat limited. Early methods included using tables, followed by floats, positioning, and inline-block elements. These techniques were essentially workarounds, lacking critical features like vertical centering. Flexbox represents a substantial advancement, yet its one-dimensional design caters to specific scenarios. Both Flexbox and Grid can synergize effectively, broadening the possibilities for responsive design. Grid stands out as the first CSS module explicitly designed to tackle the enduring layout challenges faced by web developers.
1.1. Getting Started with CSS Grid
As of March 2017, major browsers including Chrome, Firefox, Safari, and Opera offer native support for CSS Grid. This makes now the perfect time to start utilizing Grid in your projects. The fundamental steps involve setting a container element as a grid using display: grid
, defining the sizes of columns and rows with grid-template-columns
and grid-template-rows
, and positioning child elements within the grid using grid-column
and grid-row
. Similar to Flexbox, the order of elements in the source code does not dictate their visual arrangement on the page, granting you complete control over the layout through CSS.
1.2. Key Advantages of CSS Grid
- Two-Dimensional Layout: Unlike Flexbox, which is one-dimensional, Grid allows for simultaneous control over rows and columns.
- Source Order Independence: CSS can dictate the positioning of elements, enabling easy rearrangement for different screen sizes using media queries.
- Powerful Control: Grid provides a robust set of tools for managing the layout of web pages, addressing the shortcomings of previous CSS methods.
- Responsiveness: With a few lines of CSS, complete page layouts can be redefined to fit varying screen widths, making Grid exceptionally powerful.
2. Navigating CSS Grid Terminology
To fully utilize CSS Grid, it is crucial to grasp its unique terminology. Many terms may initially appear similar; however, each holds a specific meaning as defined by the Grid specification. Understanding these definitions is essential for effective communication and implementation of Grid layouts.
2.1. Essential Grid Terms
- Grid Container: The element designated as a grid using
display: grid
. It serves as the parent for all grid items. - Grid Line: The dividing lines that form the grid structure. Grid lines can be vertical (column grid lines) or horizontal (row grid lines), positioning themselves on either side of rows or columns.
- Grid Track: The space located between two adjacent grid lines. These are essentially the columns or rows that comprise the grid.
- Grid Area: The enclosed space defined by four grid lines. A grid area can include one or more grid cells.
- Grid Item: The direct children of the grid container. Only direct descendants are considered grid items, excluding any nested elements within them.
- Grid Cell: The space located between two adjacent row and column grid lines. Each cell represents a single unit within the grid structure.
3. Deep Dive into CSS Grid Properties
CSS Grid properties are divided into those that apply to the Grid Container (the parent element) and those that apply to the Grid Items (the children elements).
3.1. Properties for the Grid Container
These properties are applied to the parent element to define the grid’s structure and behavior.
3.1.1. Display
The display
property is fundamental, defining the element as a grid container.
- Values:
grid
: Creates a block-level grid.inline-grid
: Creates an inline-level grid.
.container {
display: grid | inline-grid;
}
3.1.2. Grid-Template-Columns and Grid-Template-Rows
These properties define the columns and rows of the grid.
- Values:
<track-size>
: Specifies the size of the track, which can be a length (e.g.,100px
), a percentage (e.g.,20%
), or a fraction of the free space in the grid (fr
unit).<line-name>
: Assigns a name to the grid line.
.container {
grid-template-columns: ... ...; /* e.g. 1fr 1fr minmax(10px, 1fr) 3fr repeat(5, 1fr) 50px auto 100px 1fr */
grid-template-rows: ... ...; /* e.g. min-content 1fr min-content 100px 1fr max-content */
}
Grid lines are automatically numbered, but you can explicitly name them for easier reference.
3.1.3. Grid-Template-Areas
This property defines a grid template by referencing names assigned via the grid-area
property.
- Values:
<grid-area-name>
: The name of a grid area..
: Represents an empty grid cell.none
: No grid areas are defined.
.container {
grid-template-areas:
"<grid-area-name> | . | none | ..."
"...";
}
3.1.4. Grid-Template
A shorthand for setting grid-template-rows
, grid-template-columns
, and grid-template-areas
in a single declaration.
- Values:
none
: Sets all three properties to their initial values.<grid-template-rows> / <grid-template-columns>
: Sets the respective properties to the specified values and setsgrid-template-areas
tonone
.
.container {
grid-template:
none |
<grid-template-rows> / <grid-template-columns>;
}
3.1.5. Column-Gap, Row-Gap, Grid-Column-Gap, Grid-Row-Gap
Specifies the size of the grid lines, effectively setting the width of the gutters between columns and rows.
- Values:
<line-size>
: A length value.
.container {
/* Standard */
column-gap: <line-size>;
row-gap: <line-size>;
/* Old */
grid-column-gap: <line-size>;
grid-row-gap: <line-size>;
}
3.1.6. Gap, Grid-Gap
A shorthand for row-gap
and column-gap
.
- Values:
<grid-row-gap> <grid-column-gap>
: Length values.
.container {
/* Standard */
gap: <grid-row-gap> <grid-column-gap>;
/* Old */
grid-gap: <grid-row-gap> <grid-column-gap>;
}
3.1.7. Justify-Items
Aligns grid items along the inline (row) axis.
- Values:
start
: Aligns items to the start edge of their cell.end
: Aligns items to the end edge of their cell.center
: Aligns items in the center of their cell.stretch
: Fills the whole width of the cell (default).
.container {
justify-items: start | end | center | stretch;
}
3.1.8. Align-Items
Aligns grid items along the block (column) axis.
- Values:
stretch
: Fills the whole height of the cell (default).start
: Aligns items to the start edge of their cell.end
: Aligns items to the end edge of their cell.center
: Aligns items in the center of their cell.baseline
: Aligns items along the text baseline.
.container {
align-items: start | end | center | stretch;
}
3.1.9. Place-Items
Sets both the align-items
and justify-items
properties in a single declaration.
- Values:
<align-items> / <justify-items>
: The first value setsalign-items
, and the second setsjustify-items
. If the second value is omitted, both properties are set to the first value.
.container {
place-items: <align-items> / <justify-items>;
}
3.1.10. Justify-Content
Aligns the grid within the grid container along the inline (row) axis when the grid’s total size is less than the container’s.
- Values:
start
: Aligns the grid to the start edge of the grid container.end
: Aligns the grid to the end edge of the grid container.center
: Aligns the grid in the center of the grid container.stretch
: Resizes the grid items to fill the full width of the grid container.space-around
: Places an even amount of space between each grid item, with half-sized spaces on the far ends.space-between
: Places an even amount of space between each grid item, with no space at the far ends.space-evenly
: Places an even amount of space between each grid item, including the far ends.
.container {
justify-content: start | end | center | stretch | space-around | space-between | space-evenly;
}
3.1.11. Align-Content
Aligns the grid along the block (column) axis when the grid’s total size is less than the container’s.
- Values: Same as
justify-content
.
.container {
align-content: start | end | center | stretch | space-around | space-between | space-evenly;
}
3.1.12. Place-Content
Sets both the align-content
and justify-content
properties in a single declaration.
- Values:
<align-content> / <justify-content>
: The first value setsalign-content
, and the second setsjustify-content
. If the second value is omitted, both properties are set to the first value.
.container {
place-content: <align-content> / <justify-content>;
}
3.1.13. Grid-Auto-Columns and Grid-Auto-Rows
Specifies the size of any auto-generated (implicit) grid tracks.
- Values:
<track-size>
: Specifies the size of the track.
.container {
grid-auto-columns: <track-size> ...;
grid-auto-rows: <track-size> ...;
}
3.1.14. Grid-Auto-Flow
Controls how the auto-placement algorithm works, which places items that are not explicitly positioned.
- Values:
row
: Fills in each row in turn (default).column
: Fills in each column in turn.dense
: Attempts to fill in holes earlier in the grid if smaller items come up later.
.container {
grid-auto-flow: row | column | row dense | column dense;
}
3.1.15. Grid
A shorthand for setting many of the grid properties in a single declaration.
- Values: Various, allowing you to set explicit or implicit grid properties.
.container {
grid: 100px 300px / 3fr 1fr;
}
3.2. Properties for the Grid Items
These properties are applied to the child elements of the grid container.
3.2.1. Grid-Column-Start, Grid-Column-End, Grid-Row-Start, Grid-Row-End
Determine a grid item’s location within the grid by referring to specific grid lines.
- Values:
<number> | <name>
: Refers to a numbered or named grid line.span <number> | span <name>
: The item spans across the specified number of tracks or until it hits the next line with the provided name.auto
: Indicates auto-placement or a default span of one.
.item {
grid-column-start: <number> | <name> | span <number> | span <name> | auto;
grid-column-end: <number> | <name> | span <number> | span <name> | auto;
grid-row-start: <number> | <name> | span <number> | span <name> | auto;
grid-row-end: <number> | <name> | span <number> | span <name> | auto;
}
3.2.2. Grid-Column, Grid-Row
Shorthand properties for setting the start and end lines for columns and rows.
- Values:
<start-line> / <end-line> | <start-line> / span <value>
: Each accepts the same values as the longhand versions.
.item {
grid-column: <start-line> / <end-line> | <start-line> / span <value>;
grid-row: <start-line> / <end-line> | <start-line> / span <value>;
}
3.2.3. Grid-Area
Can be used to assign a name to an item for reference by grid-template-areas
or as a shorthand for setting grid-row-start
, grid-column-start
, grid-row-end
, and grid-column-end
.
- Values:
<name>
: A name of your choosing.<row-start> / <column-start> / <row-end> / <column-end>
: Can be numbers or named lines.
.item {
grid-area:
<name> |
<row-start> / <column-start> / <row-end> / <column-end>;
}
3.2.4. Justify-Self
Aligns a grid item inside a cell along the inline (row) axis.
- Values:
start
: Aligns the grid item to the start edge of the cell.end
: Aligns the grid item to the end edge of the cell.center
: Aligns the grid item in the center of the cell.stretch
: Fills the whole width of the cell (default).
.item {
justify-self: start | end | center | stretch;
}
3.2.5. Align-Self
Aligns a grid item inside a cell along the block (column) axis.
- Values:
start
: Aligns the grid item to the start edge of the cell.end
: Aligns the grid item to the end edge of the cell.center
: Aligns the grid item in the center of the cell.stretch
: Fills the whole height of the cell (default).
.item {
align-self: start | end | center | stretch;
}
3.2.6. Place-Self
Sets both the align-self
and justify-self
properties in a single declaration.
- Values:
auto
: The “default” alignment for the layout mode.<align-self> / <justify-self>
: The first value setsalign-self
, and the second setsjustify-self
. If the second value is omitted, both properties are set to the first value.
.item {
place-self: <align-self> / <justify-self>;
}
4. Special Units and Functions in CSS Grid
CSS Grid introduces special units and functions that offer flexibility and control when defining grid layouts.
4.1. Fr Units
Fractional units (fr
) represent a portion of the remaining space in the grid container.
grid-template-columns: 1fr 3fr; /* The first column takes 25% of the space, and the second takes 75% */
4.2. Sizing Keywords
These keywords provide content-based sizing options:
min-content
: The minimum size required by the content.max-content
: The maximum size the content can take.auto
: Similar tofr
units but loses the sizing fight againstfr
units.
4.3. Sizing Functions
fit-content()
: Uses available space but stays betweenmin-content
andmax-content
.minmax()
: Sets a minimum and maximum size for a track.
grid-template-columns: minmax(100px, 1fr) 3fr; /* The column will be at least 100px but can expand to fill the remaining space */
min()
: Determines the smallest of a set of length values.max()
: Determines the largest of a set of length values.
4.4. The Repeat() Function and Keywords
The repeat()
function simplifies the definition of repeating grid tracks.
grid-template-columns: repeat(3, 1fr); /* Creates three equal-width columns */
It can be combined with keywords like auto-fill
and auto-fit
:
auto-fill
: Fills as many columns as possible, even if they are empty.auto-fit
: Fits the existing columns into the available space.
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); /* Creates as many 250px columns as possible, adjusting their width to fill the row */
5. Advanced CSS Grid Techniques
5.1. Masonry Layout
Masonry layout, which arranges elements in optimal positions based on available vertical space, is now an experimental feature in CSS Grid.
.container {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-rows: masonry;
}
5.2. Subgrid
Subgrid allows grid items to have their own grid that inherits track lines from the parent grid.
.parent-grid {
display: grid;
grid-template-columns: repeat(9, 1fr);
}
.grid-item {
grid-column: 2 / 7;
display: grid;
grid-template-columns: subgrid;
}
.child-of-grid-item {
grid-column: 3 / 6; /* Participates on the parent grid! */
}
6. Browser Support and Fluid Columns
6.1 Browser Compatibility
CSS Grid enjoys broad support across modern browsers, including Chrome, Firefox, Safari, and Edge. While Internet Explorer 11 supports an older version of the specification, utilizing modern syntax is recommended for future-proofing your code.
6.2 Achieving Fluid Columns
Crafting fluid, responsive columns that adjust based on screen availability is simplified with CSS Grid. Here’s a snippet to create columns that adapt without media queries:
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 1rem;
}
This configuration allows columns to automatically adjust, making your layout flexible across different devices.
7. CSS Grid and Animation
While CSS Grid excels in layout design, its animation capabilities are somewhat limited. The CSS Grid Layout Module Level 1 specification identifies five animatable properties, but current browser support varies:
7.1. Animatable Grid Properties
grid-gap
,grid-row-gap
,grid-column-gap
as length, percentage, or calc.grid-template-columns
,grid-template-rows
as a simple list of length, percentage, or calc.
7.2. Browser Support for Animations
- Firefox: Supports animation of
(grid-)gap
,(grid-)row-gap
,(grid-)column-gap
from version 53 andgrid-template-columns
andgrid-template-rows
from version 66. - Chrome: Supports animation of
(grid-)gap
,(grid-)row-gap
,(grid-)column-gap
from version 66. - Edge: Supports animation of
(grid-)gap
,(grid-)row-gap
,(grid-)column-gap
from version 16.
8. Practical CSS Grid Techniques
8.1. Creating a Calendar Layout
Achieve a calendar layout with minimal CSS by leveraging grid properties:
.calendar {
display: grid;
grid-template-columns: repeat(7, 1fr);
grid-gap: 10px;
}
8.2. Sticky Footer Technique
Implement a sticky footer that remains at the bottom of the page using CSS Grid:
body {
display: grid;
grid-template-rows: auto 1fr auto;
min-height: 100vh;
}
8.3. Responsive Grids Without Media Queries
Construct responsive layouts that adapt to different screen sizes without relying on media queries:
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
grid-gap: 1rem;
}
8.4. Bar Chart with CSS Grid
Build a bar chart using CSS Grid to dynamically represent data:
.bar-chart {
display: grid;
grid-template-columns: repeat(5, 1fr);
align-items: end;
}
.bar {
grid-row: 1;
}
9. CSS Grid Resources
9.1. Articles
- 4 CSS Grid Properties (and One Value) for Most of Your Layout Needs
- A Calendar in Three Lines of CSS
- A Clever Sticky Footer Technique
- A Grid of Logos in Squares
- A Lightweight Masonry Solution
- Accordion Rows in CSS Grid
- A responsive grid layout with no media queries
- An Auto-Filling CSS Grid With Max Columns of a Minimum Size
- Auto-Sizing Columns in CSS Grid:
auto-fill
vsauto-fit
- Breaking Out with CSS Grid Explained
- Bringing CSS Grid to WordPress Layouts
- Building a CSS Grid Overlay
- Building a Conference Schedule with CSS Grid
- Building a hexagonal grid using CSS grid
- Breaking the Grid
- CSS Grid and Custom Shapes, Part 1
- Cool Little CSS Grid Tricks for Your Blog
- Counting With CSS Counters and CSS Grid
- Creating a Bar Graph with CSS Grid
- CSS Grid Can Do Auto Height Transitions
- CSS Grid: One Layout, Multiple Ways
- CSS Grid Starter Layouts
- Equal Width Columns in CSS Grid are Kinda Weird
- Expandable Sections Within a CSS Grid
- Exploring CSS Grid’s Implicit Grid and Auto-Placement Powers
- Flexbox-like “just put elements in a row” with CSS grid
- Grid, content re-ordering and accessibility
- Implicit Grids, Repeatable Layout Patterns, and Danglers
- Look Ma, No Media Queries! Responsive Layouts Using CSS Grid
- Making A Bar Chart with CSS Grid
- Overlapping Header with CSS Grid
- Positioning Overlay Content with CSS Grid
- Preventing a Grid Blowout
- Simple Named Grid Areas
- Techniques for a Newspaper Layout with CSS Grid and Border Lines Between Elements
- The Holy Grail Layout with CSS Grid
- Using Position Sticky With CSS Grid
9.2. Learning Resources
- A Collection of Interesting Facts about CSS Grid Layout
- An Introduction to the
fr
CSS unit - Auto-Sizing Columns in CSS Grid:
auto-fill
vsauto-fit
- Centering in CSS Guide
- CSS Grid Layout Module Level 2
- CSS Grid in IE: CSS Grid and the New Autoprefixer
- Does CSS Grid Replace Flexbox?
- Don’t Use My Grid System (or any others)
- Exploring CSS Grid’s Implicit Grid and Auto-Placement Powers
- fit-content and fit-content()
- Getting Started with CSS Grid
- Flexbox and Grids, your layout’s best friends
- Grid Level 2 and Subgrid
- Grid for layout, flexbox for components
- Hello Subgrid
- Is CSS float deprecated?
- Quick! What’s the Difference Between Flexbox and Grid?
- Some CSS Grid Strategies for Matching Design Mockups
- The Auto-Flowing Powers of Grid’s Dense Keyword
- The Difference Between Explicit and Implicit Grids
- Things I’ve Learned About CSS Grid Layout
- Thinking Outside the Box with CSS Grid
- To grid or not to grid
- Using Grid Named Areas to Visualize (and Reference) Your Layout
- Why we need CSS subgrid
9.3. Videos
- #115: Don’t Overthink It Grids
- #019: Building a Simple Grid
- #032: Making The Grid Responsive
- #153: Getting Started with CSS Grid
- #208: A CSS Grid Layout with Pictures Down One Side Matched Up with Paragraphs on the Other
- #179: A Grid of Squares
10. Frequently Asked Questions (FAQs) about CSS Grid
-
What is CSS Grid?CSS Grid is a two-dimensional layout system that allows web developers to create complex and responsive web designs more efficiently and intuitively.
-
How does CSS Grid differ from Flexbox?CSS Grid is designed for two-dimensional layouts, managing both rows and columns, whereas Flexbox is primarily for one-dimensional content arrangement.
-
What are Grid Containers and Grid Items?A Grid Container is the parent element on which
display: grid
is applied, while Grid Items are the direct children of the Grid Container. -
How do I define the size of columns and rows in CSS Grid?You can define the size using
grid-template-columns
andgrid-template-rows
properties, specifying lengths, percentages, or fractional units (fr
). -
What are fractional units (fr) in CSS Grid?Fractional units represent a portion of the available space in the grid container. For example,
1fr
takes one part of the remaining space. -
Can I name grid lines in CSS Grid?