CSS Grid Crash Course: Mastering Two-Dimensional Layouts
This chapter provides a comprehensive introduction to CSS Grid, a powerful layout tool for web developers. We will explore the fundamental concepts of CSS Grid, compare it to Flexbox, and delve into its properties and practical applications. By the end of this chapter, you will have a solid foundation in CSS Grid and be able to create sophisticated and responsive web layouts.
1. Introduction to CSS Grid
CSS Grid is a layout system that enables web developers to create complex two-dimensional layouts for web pages. It allows for precise control over the positioning and sizing of elements in both rows and columns.
CSS Grid: A two-dimensional layout system in CSS that allows for the creation of complex web page layouts using rows and columns. It provides powerful tools for aligning and distributing space among items in a grid container.
1.1. CSS Grid vs. Flexbox: Choosing the Right Tool
Often, web developers wonder whether to use CSS Grid or Flexbox for layout purposes. While both are powerful CSS layout modules, they are designed for different scenarios.
Flexbox: A one-dimensional layout model in CSS, primarily designed for arranging items in a single row or column. It is excellent for distributing space among items within a container and for alignment along a single axis.
Flexbox, which was introduced earlier, excels at one-dimensional layouts – arranging items in a single row or column. It’s ideal for aligning elements within components. CSS Grid, on the other hand, is designed for two-dimensional layouts, allowing you to control both rows and columns simultaneously.
Key Differences and Usage Recommendations:
- Layout Dimension:
- Flexbox: One-dimensional (primarily rows or columns).
- CSS Grid: Two-dimensional (rows and columns simultaneously).
- Ideal Use Cases:
- Flexbox: Aligning items within a component (e.g., navigation bar items, card content).
- CSS Grid: Overall page layout, structuring major sections of a website (e.g., headers, footers, sidebars, content areas, card grids).
- Browser Compatibility:
- Flexbox: Generally has broader browser compatibility, including older browsers.
- CSS Grid: Excellent support in modern browsers. For modern front-end development, browser compatibility is generally not a significant concern for either.
Personal Workflow Recommendation:
A common and effective approach is to combine both CSS Grid and Flexbox:
- CSS Grid for Overall Layout: Use CSS Grid to structure the main areas of a website or user interface (UI), such as headers, navigation, main content areas, sidebars, and footers.
- Flexbox for Component Layout: Utilize Flexbox for aligning elements within individual components, like elements within a card, navigation items, or form controls.
User Interface (UI): The visual part of an application or website that allows users to interact with it. It includes all the elements that users see and interact with, such as buttons, menus, and text.
Ultimately, the choice between Grid and Flexbox often comes down to preference and the specific layout requirements. Learning both will significantly enhance your front-end development toolkit, allowing you to choose the most appropriate tool for each task.
Front-end development: The practice of creating the user-facing part of websites and web applications. It involves using HTML, CSS, and JavaScript to build interactive and visually appealing interfaces.
2. CSS Grid Fundamentals: Containers and Items
Just like Flexbox, CSS Grid operates on the concept of containers and items.
Container: In CSS Grid, the parent element on which
display: grid;
is applied, making it a grid layout. It defines the overall grid structure.
Item: In CSS Grid, direct children of the grid container. These elements are positioned and sized according to the grid layout rules defined on the container.
To create a CSS Grid layout, you first designate an HTML element as a grid container by setting its display
property to grid
. All direct children of this container then become grid items.
.container {
display: grid; /* Declares .container as a grid container */
}
Display Property: A fundamental CSS property that determines the type of box an element generates. Setting
display: grid;
ordisplay: flex;
activates the respective layout module.
2.1. Grid Container Properties
Once an element is established as a grid container, you can apply specific CSS properties to control its grid structure and the behavior of its items.
2.1.1. grid-template-columns
This property defines the columns of the grid. You specify the width of each column using various units, such as pixels (px
), percentages (%
), or fractional units (fr
).
grid-template-columns
: A CSS Grid property used on the grid container to define the number and size of columns in the grid layout. It accepts a space-separated list of values, each specifying the width of a column.
Example:
.container {
display: grid;
grid-template-columns: 100px 200px 300px; /* Creates three columns with widths 100px, 200px, and 300px */
}
You can also use percentages for responsive column widths:
.container {
display: grid;
grid-template-columns: 30% 40% 30%; /* Three columns with percentage-based widths */
}
However, the most common and flexible unit for grid-template-columns
(and grid-template-rows
) is the fractional unit, fr
.
Fractional Unit (fr): A unit in CSS Grid that represents a fraction of the available space in the grid container.
1fr
represents one equal share of the remaining space after other columns or rows have been sized.
Using fr
units allows columns to responsively resize and fill the available space:
.container {
display: grid;
grid-template-columns: 1fr 1fr; /* Creates two equal-width columns that share available space */
}
For creating repeating column patterns, the repeat()
function is highly useful.
repeat()
function: A CSS function used withingrid-template-columns
andgrid-template-rows
to define repeating patterns of column or row sizes. It simplifies the definition of grids with many identical columns or rows.
Example:
.container {
display: grid;
grid-template-columns: repeat(3, 1fr); /* Creates three equal-width columns using repeat function */
}
This is equivalent to writing grid-template-columns: 1fr 1fr 1fr;
.
2.1.2. grid-template-rows
Similar to grid-template-columns
, grid-template-rows
defines the rows of the grid. It specifies the height of each row using units like pixels, percentages, or fractional units.
grid-template-rows
: A CSS Grid property used on the grid container to define the number and size of rows in the grid layout. It functions similarly togrid-template-columns
, but for rows.
Example:
.container {
display: grid;
grid-template-rows: 200px 100px 200px; /* Creates three rows with heights 200px, 100px, and 200px */
}
Often, the height of rows is determined by their content, making explicit grid-template-rows
definitions less common for typical website layouts. However, it’s valuable for scenarios where you need fixed or specific row heights.
2.1.3. column-gap
, row-gap
, and gap
These properties control the spacing between grid items.
column-gap
: Sets the gap size between columns.row-gap
: Sets the gap size between rows.gap
: A shorthand property to set bothrow-gap
andcolumn-gap
simultaneously.
column-gap
: A CSS Grid property that specifies the size of the gutter (space) between columns in a grid layout.
row-gap
: A CSS Grid property that specifies the size of the gutter (space) between rows in a grid layout.
gap
: A CSS Grid shorthand property for setting bothrow-gap
andcolumn-gap
at once. If one value is provided, it applies to both rows and columns. If two values are provided, the first setsrow-gap
and the second setscolumn-gap
.
Example:
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px; /* Sets both row-gap and column-gap to 10 pixels */
/* or */
row-gap: 10px;
column-gap: 10px; /* Equivalent to gap: 10px; */
}
Using gap
is often preferred for its conciseness.
2.1.4. grid-auto-rows
This property defines the size of implicitly created rows. Implicit rows are generated when grid items are placed outside of the rows explicitly defined by grid-template-rows
. grid-auto-rows
sets a default height for these rows.
grid-auto-rows
: A CSS Grid property that defines the size of rows that are implicitly created by the grid layout algorithm. This is useful when grid items are placed in rows that are not explicitly defined ingrid-template-rows
.
Example:
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-rows: 200px; /* Sets the height of any implicitly created rows to 200 pixels */
}
2.1.5. minmax()
function
The minmax()
function is a powerful tool for setting flexible size ranges for grid rows and columns. It allows you to define a minimum and maximum size for a track (row or column).
minmax()
function: A CSS function used ingrid-template-columns
andgrid-template-rows
to define a size range for grid tracks. It takes two arguments: a minimum size and a maximum size, allowing tracks to be responsive within a specified range.
Syntax: minmax(minimum, maximum)
Example:
.container {
display: grid;
grid-template-columns: repeat(3, minmax(100px, 1fr)); /* Columns with a minimum width of 100px, expanding to fill available space */
grid-auto-rows: minmax(100px, auto); /* Rows with a minimum height of 100px, expanding to fit content */
}
In this example:
- Columns will be at least
100px
wide, but can grow to take up equal fractions of the available space (1fr
). - Rows will be at least
100px
tall, but will automatically adjust their height (auto
) to accommodate their content.
2.1.6. Alignment Properties: align-items
, justify-content
CSS Grid provides alignment properties similar to Flexbox, but they operate in two dimensions within the grid container.
align-items
: Controls the vertical alignment of grid items within their grid areas.justify-content
: Controls the horizontal alignment of the grid tracks within the grid container.
align-items
: A CSS Grid property that sets the default vertical alignment of grid items within their grid areas. It is applied to the grid container and affects all grid items.
justify-content
: A CSS Grid property that sets the horizontal alignment of grid tracks (columns) within the grid container. It controls how space is distributed around and between columns when the total width of columns is less than the width of the grid container.
Common Values for align-items
:
stretch
(default): Items stretch to fill the height of their grid area.start
: Items align to the top of their grid area.center
: Items align to the vertical center of their grid area.end
: Items align to the bottom of their grid area.
Common Values for justify-content
:
stretch
(default): Grid tracks stretch to fill the width of the grid container.start
: Grid tracks are aligned to the left of the grid container.center
: Grid tracks are centered within the grid container.end
: Grid tracks are aligned to the right of the grid container.space-around
: Distributes space evenly around each grid track, with half-size spaces at the ends.space-between
: Distributes space evenly between grid tracks, with no space at the ends.space-evenly
: Distributes space evenly between grid tracks, including the ends.
Example:
.container {
display: grid;
grid-template-columns: repeat(3, 100px); /* Fixed width columns for demonstration */
justify-content: center; /* Horizontally center grid tracks */
align-items: center; /* Vertically center grid items in their areas */
height: 500px; /* Set container height to visualize vertical alignment */
}
2.1.7. Self-Alignment Properties: align-self
, justify-self
To override the default alignment set by align-items
and justify-content
for individual grid items, you can use:
align-self
: Controls the vertical alignment of a specific grid item within its grid area.justify-self
: Controls the horizontal alignment of a specific grid item within its grid area.
align-self
: A CSS Grid property that allows you to override thealign-items
property for a specific grid item, controlling its vertical alignment within its grid area.
justify-self
: A CSS Grid property that allows you to override thejustify-content
property for a specific grid item, controlling its horizontal alignment within its grid area.
Example:
.item-2 { /* Selects the second grid item */
align-self: end; /* Vertically aligns item-2 to the bottom of its grid area */
justify-self: center; /* Horizontally centers item-2 within its grid area */
}
You can target specific grid items using CSS selectors, including pseudo-selectors like :nth-of-type()
.
Pseudo-selector: In CSS, a keyword added to a selector that specifies a special state of the selected element(s). For example,
:hover
to style an element when the mouse cursor is over it, or:nth-of-type()
to select elements based on their position among siblings of the same type.
Example using :nth-of-type()
:
.item:nth-of-type(2) { /* Targets the second element with class .item */
align-self: end;
justify-self: center;
}
2.2. Spanning Grid Items
CSS Grid allows items to span across multiple rows and columns, creating more complex layouts. This is achieved using the following properties on grid items:
2.2.1. grid-column-start
, grid-column-end
, and grid-column
These properties control the horizontal placement and span of a grid item. Grid lines are numbered starting from 1, defining the boundaries of columns and rows.
grid-column-start
: Specifies the starting column line of the grid item.grid-column-end
: Specifies the ending column line of the grid item.grid-column
: Shorthand property for setting bothgrid-column-start
andgrid-column-end
.
grid-column-start
: A CSS Grid property that specifies the starting column line for a grid item, determining where it begins horizontally in the grid.
grid-column-end
: A CSS Grid property that specifies the ending column line for a grid item, determining where it ends horizontally in the grid.
grid-column
: A CSS Grid shorthand property for setting bothgrid-column-start
andgrid-column-end
in a single declaration. It uses a syntax likestart-line / end-line
(e.g.,grid-column: 1 / 3;
).
Example:
.item-1 { /* Selects the first grid item */
grid-column-start: 1; /* Start at column line 1 */
grid-column-end: 3; /* End at column line 3 (span 2 columns) */
/* or shorthand */
grid-column: 1 / 3; /* Equivalent to the above */
}
You can also use the span
keyword with grid-column
to specify the number of columns to span from the starting line.
Example using span
:
.item-1 {
grid-column: 1 / span 2; /* Start at column line 1 and span 2 columns */
}
2.2.2. grid-row-start
, grid-row-end
, and grid-row
These properties are analogous to the column properties but control the vertical placement and span of a grid item across rows.
grid-row-start
: Specifies the starting row line of the grid item.grid-row-end
: Specifies the ending row line of the grid item.grid-row
: Shorthand property for setting bothgrid-row-start
andgrid-row-end
.
grid-row-start
: A CSS Grid property that specifies the starting row line for a grid item, determining where it begins vertically in the grid.
grid-row-end
: A CSS Grid property that specifies the ending row line for a grid item, determining where it ends vertically in the grid.
grid-row
: A CSS Grid shorthand property for setting bothgrid-row-start
andgrid-row-end
in a single declaration. It uses a syntax likestart-line / end-line
(e.g.,grid-row: 2 / 4;
).
Example:
.item-3 { /* Selects the third grid item */
grid-row-start: 2; /* Start at row line 2 */
grid-row-end: 4; /* End at row line 4 (span 2 rows) */
/* or shorthand */
grid-row: 2 / 4; /* Equivalent to the above */
}
Similarly to grid-column
, you can use span
with grid-row
.
Example using span
:
.item-3 {
grid-row: 2 / span 2; /* Start at row line 2 and span 2 rows */
}
2.3. Responsiveness with CSS Grid
CSS Grid is inherently responsive and works well with media queries to adapt layouts for different screen sizes.
Responsiveness: In web design, the ability of a website or application to adapt its layout and content to different screen sizes and devices, ensuring optimal viewing and user experience across various platforms.
Media Queries: A CSS technique that allows you to apply different styles based on characteristics of the device or browser being used, such as screen width, height, resolution, and orientation. They are crucial for creating responsive web designs.
2.3.1. Media Queries for Grid Layouts
By using media queries, you can modify grid properties like grid-template-columns
and grid-template-rows
at different breakpoints, creating layouts that reflow and adjust as the screen size changes.
Breakpoint: In responsive web design, a specific screen width at which the layout of a website or application changes to better suit different devices. Media queries are used to define styles for different breakpoints.
Example:
.container {
display: grid;
grid-template-columns: repeat(3, 1fr); /* Default 3-column layout */
}
@media (max-width: 500px) { /* Media query for screens smaller than 500px */
.container {
grid-template-columns: 1fr; /* Change to a single-column layout on small screens */
}
}
In this example, the grid defaults to a three-column layout. When the screen width is less than or equal to 500 pixels (a common breakpoint for mobile devices), the layout switches to a single column, stacking the grid items vertically.
2.3.2. auto-fill
and minmax()
for Flexible Columns
For layouts where you want columns to automatically wrap and adjust based on content and screen width, you can combine repeat()
, auto-fill
, and minmax()
.
auto-fill
: A keyword used in therepeat()
function withingrid-template-columns
andgrid-template-rows
. It instructs the grid to repeat tracks as many times as possible to fit within the container’s dimensions without overflowing, creating as many columns or rows as can fit.
Example:
.container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); /* Responsive columns that wrap and adjust */
}
Here, auto-fill
tells the grid to create as many columns as it can fit within the container’s width. minmax(200px, 1fr)
ensures each column is at least 200 pixels wide but can expand to take up an equal fraction of the available space (1fr
). As the container width decreases, columns will wrap to the next row when they can no longer fit at their minimum width.
2.4. Grid Template Areas: Visual Layout Definition
grid-template-areas
provides a visually intuitive way to define grid layouts using named areas within the grid container.
grid-template-areas
: A CSS Grid property that allows you to define a grid layout by naming grid areas and arranging them in a visual representation within the CSS code. It provides a more intuitive way to create layouts, especially for complex structures.
This method involves:
- Naming Grid Areas: Assign names to specific areas within your layout within the
grid-template-areas
property. - Assigning Areas to Items: Use the
grid-area
property on grid items to associate them with the named areas defined ingrid-template-areas
.
grid-area
: A CSS Grid property used on grid items to assign them to named grid areas defined ingrid-template-areas
. It can also be used as a shorthand to setgrid-row-start
,grid-column-start
,grid-row-end
, andgrid-column-end
in a single declaration.
Example:
HTML Structure:
<body>
<header>Header</header>
<nav>Navigation</nav>
<main>Content</main>
<aside>Sidebar</aside>
<footer>Footer</footer>
</body>
CSS Styling:
body {
display: grid;
grid-template-areas:
"header header header"
"nav content sidebar"
"nav footer footer";
grid-template-columns: 1fr 4fr 1fr; /* Define column widths */
grid-template-rows: 80px 1fr 70px; /* Define row heights */
height: 100vh; /* Set body height to viewport height */
}
header { grid-area: header; }
nav { grid-area: nav; }
main { grid-area: content; }
aside { grid-area: sidebar; }
footer { grid-area: footer; }
header, nav, main, aside, footer {
background-color: steelblue;
color: white;
padding: 20px;
border: 1px solid skyblue;
}
In this example:
grid-template-areas
visually defines a 3x3 grid structure using area names.- Each row in
grid-template-areas
represents a row in the grid. - Area names (e.g., “header”, “nav”, “content”) are used to define the layout.
- The
grid-area
property on each HTML element assigns it to the corresponding named area. grid-template-columns
andgrid-template-rows
define the sizes of the grid tracks.
This approach offers a clear and maintainable way to visualize and define complex layouts directly in your CSS. While not always necessary, grid-template-areas
are particularly useful for page-level layouts with distinct sections.
Viewport height (vh): A CSS unit that represents 1/100th of the height of the viewport (the visible area of the browser window).
100vh
is equal to the full height of the viewport.
3. Project: Testimonials Grid Section
To solidify your understanding of CSS Grid, let’s build a practical project: a testimonials grid section inspired by Frontend Mentor challenges. This project showcases the power of CSS Grid for creating intricate layouts, including spanning items across rows and columns.
Frontend Mentor: An online platform that provides coding challenges for web developers to improve their HTML, CSS, and JavaScript skills. It offers a range of projects with varying difficulty levels and design specifications.
Testimonials: Statements or endorsements from satisfied customers or users, often used to build trust and credibility for a product or service.
For this project, we will create a grid layout for displaying testimonial cards. Some cards will span multiple columns and rows, demonstrating advanced grid layout techniques.
3.1. HTML Structure (Simplified)
<div class="testimonials">
<div class="card card--bg-purple">
<header class="card__header">...</header>
<p class="card__lead">...</p>
<p class="card__quote">...</p>
</div>
<div class="card card--bg-gray-blue">...</div>
<div class="card">...</div>
<div class="card card--bg-black-blue">...</div>
<div class="card">...</div>
</div>
<footer class="footer">...</footer>
We use a container with the class .testimonials
as our grid container. Inside, we have several .card
elements representing individual testimonials. Some cards have modifier classes like .card--bg-purple
for styling variations.
BEM Syntax: (Block, Element, Modifier) A popular CSS naming convention that aims to make class names more descriptive and maintainable. It structures class names as
block__element--modifier
.
3.2. CSS Styling (Grid Implementation)
.testimonials {
display: grid;
grid-template-columns: repeat(4, 1fr); /* 4-column grid */
gap: 30px;
max-width: 1440px;
margin: 100px auto;
}
.card--bg-purple { /* Styling for purple background card */
background-color: hsl(263, 55%, 52%);
background-image: url("./images/bg-pattern-quotation.svg");
background-repeat: no-repeat;
background-position: top right;
}
/* ... other card styling ... */
/* Spanning Items */
.card:nth-of-type(1) {
grid-column: 1 / 3; /* Span columns 1 and 2 */
}
.card:nth-of-type(4) {
grid-column: 2 / 4; /* Span columns 2 and 3 */
grid-row: 2; /* Position in the second row */
}
.card:nth-of-type(5) {
grid-column: 4; /* Position in the fourth column */
grid-row: 1 / 3; /* Span rows 1 and 2 */
}
/* Responsive Adjustments */
@media (max-width: 768px) {
.testimonials {
grid-template-columns: 1fr; /* Single-column layout on smaller screens */
}
.card:nth-of-type(1) {
grid-column: 1; /* Reset column span */
}
.card:nth-of-type(4) {
grid-column: 1; /* Reset column span */
grid-row: 4; /* Reposition in the fourth row */
}
.card:nth-of-type(5) {
grid-column: 1; /* Reset column span */
grid-row: 5; /* Reposition in the fifth row */
}
}
In this CSS:
.testimonials
is set as a grid container with a 4-column layout.gap
adds spacing between cards.- Modifier classes like
.card--bg-purple
apply specific styling (e.g., background color, quote image). :nth-of-type()
selectors target specific cards to apply column and row spans.- A media query adjusts the layout to a single column on smaller screens, resetting spans as needed.
HSL color values: (Hue, Saturation, Lightness) A color model in CSS that defines colors using hue (color type), saturation (intensity), and lightness (brightness). HSL is often considered more intuitive than RGB for adjusting colors.
This project demonstrates how CSS Grid can be used to create complex, responsive layouts with items spanning multiple grid tracks. By adjusting grid properties and using media queries, you can achieve sophisticated designs that adapt gracefully to different screen sizes.
4. Conclusion
CSS Grid is a powerful and versatile layout tool that significantly enhances your ability to create complex and responsive web designs. By understanding its fundamental concepts, properties, and techniques like spanning and grid template areas, you can build sophisticated layouts that were previously challenging to achieve with older CSS methods. Combining CSS Grid with Flexbox provides a comprehensive toolkit for tackling virtually any layout challenge in modern web development. Continued practice and exploration of project-based tutorials will further solidify your CSS Grid skills and empower you to create stunning and functional web interfaces.