Mastering CSS Grid - Pascal Thormeier - E-Book

Mastering CSS Grid E-Book

Pascal Thormeier

0,0
27,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

CSS Grid has revolutionized web design by filling a long-existing gap in creating real, dynamic grids on the web. This book will help you grasp these CSS Grid concepts in a step-by-step way, empowering you with the knowledge and skills needed to design beautiful and responsive grid-based layouts for your web projects.


This book provides a comprehensive coverage of CSS Grid by taking you through both fundamental and advanced concepts with practical exercises. You'll learn how to create responsive layouts and discover best practices for incorporating grids into any design. As you advance, you'll explore the dynamic interplay between CSS Grid and flexbox, culminating in the development of a usable responsive web project as a reference for further improvement. You'll also see how frameworks utilize CSS Grid to construct reusable components and learn to rebuild and polyfill CSS Grid for browsers that don't fully support it yet. The concluding chapters include a quick reference and cheat sheet, making this book an indispensable resource for frontend developers of all skill levels.


By the end of this book, you'll have thoroughly explored all aspects of CSS Grid and gained expert-level proficiency, enabling you to craft beautiful and functional layouts for web projects of any size.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 328

Veröffentlichungsjahr: 2023

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Mastering CSS Grid

A comprehensive and practical guide to creating beautiful layouts with CSS Grid

Pascal Thormeier

BIRMINGHAM—MUMBAI

Mastering CSS Grid

Copyright © 2023 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Rohit Rajkumar

Publishing Product Manager: Bhavya Rao

Content Development Editor: Abhishek Jadhav

Technical Editor: Simran Udasi

Copy Editor: Safis Editing

Project Coordinator: Manthan Patel

Proofreader: Safis Editing

Indexer: Sejal Dsilva

Production Designer: Joshua Misquitta

Marketing Coordinator: Nivedita Pandey

First published: June 2023

Production reference: 2110723

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80461-484-6

www.packtpub.com

To my parents, Marlies and Michael, my sister, Sandra, and my grandparents Hannelore and Lothar for teaching me to stay curious and that technology and numbers are fun, and for supporting me every step of the way. To all my co-workers at Liip for their vast knowledge and expertise, from which I learned a ton. To my partner, Denise, for supporting me endlessly in all my endeavors and always offering a second brain for many challenges. Without you, this book would not have been possible!

– Pascal Thormeier.

Contributors

About the author

Pascal Thormeier, born in 1990, is a senior software developer at Liip AG, a leading Swiss web agency, and he considers himself at home in both the frontend and backend. Initially programming in PHP as his first language in the early 2000s, Pascal has experience in many technologies, languages, and frameworks, such as Java, Python, NodeJS, and Vue.

After 4 years of part-time studying, Pascal received a bachelor’s degree in computer science with a specialization in design and management from the University of Applied Sciences and Arts Northwestern Switzerland in 2020, and he started to write a tech blog on dev.to shortly after. He has since published over 75 articles and an online course on Vue.

I want to thank those who supported and challenged me during the writing process, especially my co-workers at Liip and my partner. I love you, Denise!

About the reviewers

Giuseppe Caruso started his career when the most used web framework was an HTML table and spacer.gif was a thing. In response to the misuse of tables, he donned a blue beanie and began to develop websites with web standards. CSS taught him, in a lot of quirks modes, that position is everything.

He is a senior frontend developer, with expertise in building design systems with CSS and semantic and accessible HTML. His background in architecture and design made him passionate about bridging the gap between developers and designers.

He has worked for many kinds of companies, from medium start-ups such as Tado to larger public companies such as Trivago. Currently, he is part of the Digital Incubator team, shaping the future at Vodafone GmbH in lovely Düsseldorf.

I would like to thank Alice for her unwavering support and love throughout the journey we call life. She is my wonderland.

I am grateful to my son, Nicola, who through his own eyes, makes me a better person every day. He constantly surprises me with his courage, his wisdom, and his smile.

Lastly, I would like to thank Patrick for being a friend, a mentor, and a constant source of inspiration. You are my favorite alien.

Michelle Manemann is a seasoned veteran of the publishing industry, having created hundreds of custom websites for her company over the past decade. Her previous experience as a technical reviewer includes Responsive Web Design with HTML5 and CSS, published by Packt in 2022.

Upon graduating from Grinnell College, she established a full-fledged web design department. Under her leadership, her team crafts captivating websites for educators across North America. She is dedicated to creating environments – online and in person – that favor inclusion and accessibility for all.

When business hours are over, Michelle is on the move, exploring the natural beauty along her native Mississippi River or traveling the world to uncover new founts of inspiration.

My success is due to the unconditional love of my family, including my parents and brother. I am grateful for their support, which blossomed from loving roots planted by my grandmothers, Mary Kay and Debbie. My gratitude is as endless as their devotion to us all.

Sabya Sachi is a passionate UI developer and has been working in the IT industry for the past 11 years. He graduated in computer science engineering from Rajasthan Technical University, Kota.

He mostly spends his time with CSS, HTML, JavaScript, and other UI frameworks/libraries. He has worked with a few big MNC companies, such as L&T Infotech, Fidelity Investments, Mu Sigma, Empower Retirement, and Omnicom Media Group. He has designed a few responsive websites for his clients.

Exploring the world of CSS is his passion. He has also architected, designed, and migrated web apps, always adhering to normalized CSS layouts, responsive designing, and optimal practices. He has also optimized web app performance on the existing development.

The latest trend in CSS, HTML, and JavaScript keeps him busy all the time.

Table of Contents

Preface

Part 1–Working with CSS Grid

1

Understanding the Basic Rules and Structures for CSS Grid

Technical requirements

Understanding the basic rules related to CSS Grid

Defining grid terminology

Creating our first grid

Arranging grid elements

Adding some breathing room (or gaps)

Using grid templates

Naming grid rows and columns

Grid flow

Understanding special grid-related units, keywords, and functions

The fractional unit

Sizing keywords and functions

Repetitive column and row definitions

Using shortcuts

The grid attribute

The grid-template attribute

The grid-row and grid-column attributes

The gap attribute

Summary

2

Project Introduction: What We’ll Work on and First Tasks

Technical requirements

Introducing Awesome Analytics – our gibberish analytics tool

Setting up Awesome Analytics locally

Receiving our first task – implementing the grids

Exploring the code of Awesome Analytics

The CSS structure

The HTML structure

The JavaScript structure

Fixing Awesome Analytics’ layout problem – a possible solution

Analyzing the problem

Creating the page layout

Arranging the chart boxes

Summary

3

Building Advanced Grid Layouts

Technical requirements

Understanding the row axis and column axis and how to influence them

Arranging grid items and grid cells with alignment and justification rules

Aligning and justifying items

Aligning and justifying the entire grid within its container

Defining and using advanced grid templates

Defining empty cells in grid area templates

Naming grid areas implicitly

Practicing creating flexible layouts with JavaScript

Arranging nested child elements in parent grids

Creating subgrids

Understanding how subgrids work

Understanding what is inherited

Understanding subgrids’ current state of development (as of 2023)

Masonry layouts

Understanding what masonry layouts are

Using masonry layouts with CSS Grid and knowing about its pitfalls

Practicing with Awesome Analytics

Receiving the task

Implementing a possible solution

Summary

Part 2 – Understanding the CSS Grid Periphery

4

Understanding and Creating Responsive and Fluid Grid Layouts

Technical requirements

Understanding the challenges of designing layouts

Existing things

The content

The target groups

The stakeholders

The web design principles

Understanding the difference between adaptive, responsive, and fluid layouts

Adaptive layouts

Responsive layouts

Fluid layouts

Learning responsive layout best practices

Prioritizing content

Applying mobile first

Designing with worst-case content in mind

Combining adaptiveness, responsiveness, and fluidity

Implementing responsive and fluid layouts with CSS Grid

Media queries and altering grid area templates

Using sizing keywords and functions for fluid layouts

Practicing responsive layouts with Awesome Analytics

The task at hand

A possible solution

Summary

5

Implementing Layouts with Flexbox and CSS Grid

Technical requirements

Arranging media objects

Arranging teasers and card elements

Arranging forms and form elements

Input groups

Compound form elements

Form layouts

Building page layouts and partials

Headers and navigation

Footers

Building entire pages

Practicing with Awesome Analytics

Analyzing the code base

Adjusting the header

Adjusting the chart boxes

Adjusting the page layout

Adjusting the chart box container

Conclusion

Summary

6

Benefits of Grid Layouts and When Not to Use Them

Technical requirements

Cherishing the benefits of grid layouts

The ease of design and development

Visual appeal

Simple to adapt and expand

Understanding the drawbacks of grid layouts

Compatibility with content

Losing identity

The temptation of packing things too tight

Being restricted

Learning about some alternatives for grid layouts

Breaking out of the grid

Using animations

Using different shapes

A list to help us decide

Summary

Part 3 – Exploring the Wider Ecosystem

7

Polyfilling CSS Grid’s Missing Features

Technical requirements

Understanding the tools to write a CSS polyfill from scratch

Understanding PostCSS

Understanding how to write PostCSS plugins

Understanding Browserify

Tying loose ends

Creating a polyfill for subgrid

Understanding how subgrid is meant to work

Why and when the polyfill may be useful

Writing a polyfill

Why we shouldn’t use this polyfill

Creating a polyfill for masonry

Understanding how masonry is meant to work

Why and when the polyfill may be useful

Writing the polyfill

Why we shouldn’t use this polyfill

Creating a polyfill for additional pseudo-classes

Understanding the idea behind nth-row and nth-col

Why and when the polyfill may be useful

Writing the polyfill

Why we shouldn’t use this polyfill

Animating grids

Understanding the goal of grid animations

Using the animate-css-grid library

Understanding why we should not use polyfills

Summary

8

Grids in the Wild – How Frameworks Implement Grids

Technical requirements

Learning how Tailwind implements grids

Learning how Bootstrap implements grids

Learning how Foundation implements grids

Float grid

Flex grid

XY grid

Learning how Bulma.io implements grids

Learning how UIkit implements grids

Learning how Pure.css implements grids

Learning how Tachyons implements grids

Learning how Cutestrap implements grids

Learning how other frameworks don’t implement grids

Practising Bootstrap and Tailwind frameworks with AwesomeAnalytics

Implementing Tailwind’s grid

Implementing Bootstrap’s grid

Summary

Part 4 – A Quick Reference

9

Quick Reference and Cheat Sheet

Technical requirements

Important terms and their definitions

CSS Grid attributes, values, functions, and units

Display property values

CSS Grid recipes for everyday use cases

Holy grail layouts

Responsive Holy grail layouts using grid areas

Dashboard box arrangement

A fluid image gallery with a fixed aspect ratio and minimum element width

Media objects

Full-height pages with a sticky header

Screen-filling sections for landing pages

Gantt charts

Grid design best practices and do’s and don’ts

A framework cheat sheet for the Holy grail layout

Tailwind

Bootstrap

Foundation (XY Grid only)

Bulma.io

UIKit

Pure.css

Tachyons

Cutestrap

Summary

Index

Other Books You May Enjoy

Preface

Hello, world! With this book, you hold a guide to a CSS feature that the entire frontend development community has longed for since the early days of HTML and CSS – CSS Grid. This book covers all of CSS Grid:

The basicsThe advanced thingsHow grids can be used in designWhen not to use grids at allCSS Grid’s relation to its cousin Flexbox

You will also find an exhaustive cheat sheet and quick reference at the end of the book.

However, before we dive into the details, let me take you on a journey into the early 2000s, when I started to learn to program while still in high school.

Back then, before the invention of smartphones – the first iPhone was released in June 2007 – we didn’t have much. CSS 2 was the current version, with CSS 2.1 not being released until 2011. CSS 2 was the version that brought us relative and absolute positioning, but we would not get the first version of Flexbox until 2015, and CSS Grid only in 2018.

According to legend, the original purpose of HTML was to display scientific papers. In any case, scientific papers don’t need precise, fancy layouts. Instead, they need typography, such as headings and paragraphs, images, and tables.

However, as soon as the World Wide Web took off, people did come up with fancy layouts, and they used the tools at hand. For example, if configured suitably, you can use a table to build something that resembles a grid layout. And that’s what we did – all the time, everywhere.

At some point, people started using floating elements. This feature was initially intended to make text float around images and other objects, but it was more or less instantly used as a layout tool for entire websites.

We defined a grid with the width of the elements and their position in a document. So, for example, a header would have a width of 100% and not be floating, whereas a sidebar with navigation would be considered a left-floating element or, at times, a right-floating one if you wanted your website to be unique.

We slowly start to see a pattern here. In the early days, people used tools in ways they were not intended. There’s nothing wrong with that; that’s how innovation happens. A quote by the famous webcomic Saturday Morning Breakfast Cereal that I love even says that the “deep abiding goal of any engineer is to take a thing and make it do a thing it wasn’t meant to do.” And that’s fine!

There are issues, however. The problems with table layouts and floating elements were manifold. First, they needed a large amount of boilerplate code and sometimes felt like pure magic. To correctly align floating elements, we must also consider all elements around them.

Second, a table is a way of displaying data, not a layout tool. People were not nearly as aware of accessibility as they are today, and we still have room for improvement. When early screen readers encountered a table, they interpreted it as a table. And tables have data, not navigations.

Flexbox solved many positioning problems. There were many tricks to center-align elements both vertically and horizontally. Some are still viable today. Flexbox simplified the task, and the code was much more straightforward. The intent of display: flex; justify-content: center; is much more explicit than the one of margin: 0 auto;.

But what ultimately happened was that people – again – used Flexbox to create grid layouts almost immediately. Many frameworks offer a .container CSS class that applies Flexbox to the element and then works with column classes to achieve a horizontal grid. Vertical grids work with nested flexboxes. So, Flexbox is a layout tool, but we still needed to go one or two steps further for grids.

With the release of CSS Grid, developers finally got what they had improvised since the inception of the World Wide Web – a working grid layout tool. Finally, we could build grids as they had been implemented in many other languages and frameworks for ages. For reference, the oldest occurrence of JavaFX’s GridPane I could find on the web is from 2003, almost 15 years before the production-readiness of CSS Grid.

And with this, our little journey through the decades is over. Today, thanks to the deprecation of Microsoft’s Internet Explorer 11 in 2022, every significant browser fully supports CSS Grid. As a result, we can use it to finally live up to the fantastic designs UX experts come up with and use grids, instead of thinking about how we can make something behave like a grid.

However, there is one use case for which we still need to go back to nested tables, floating elements, and non-Flexbox, non-CSS Grid layouts – email templates. Of course, there are solutions to that, too, but that’s a different story.

Who this book is for

This book is for aspiring (frontend) web developers who want to improve their layout skills and learn the ins and outs of this magnificent tool.

This book may also benefit UX experts with a rudimentary knowledge of frontend development who want to learn an effective tool to create prototypes faster.

What this book covers

Chapter 1, Understanding the Basic Rules and Structures for CSS Grid, covers the fundamentals, such as grid terminology, creating your first grids, arranging grid elements, and grid templates.

Chapter 2, Project Introduction: What We’ll Work on and First Tasks, introduces the accompanying project that we will work on throughout the book.

Chapter 3, Building Advanced Grid Layouts, introduces advanced features of CSS Grid, such as the row and column axes, how to align and justify grid content, and advanced grid templates.

Chapter 4, Understanding and Creating Responsive and Fluid Grid Layouts, covers what responsive and fluid layouts are, what best practices exist, and how to build the layouts with CSS Grid.

Chapter 5, Implementing Layouts With Flexbox and CSS Grid, explores the differences and similarities between CSS Grid and Flexbox and their specific use cases.

Chapter 6, Benefits of Grid Layouts and When Not to Use Them, discusses the benefits and drawbacks of grid layouts related to design and usability and introduces alternative layout methods.

Chapter 7, Polyfilling CSS Grid’s Missing Features, introduces PostCSS and JavaScript to implement missing features and better understand how they will work once introduced.

Chapter 8, Grids in the Wild – How Frameworks Implement Grids, discusses the different approaches to the grids of eight different CSS frameworks while explaining how to implement standard use cases.

Chapter 9, Quick Reference and Cheat Sheet, gives a condensed overview of all CSS Grid features, terminology, and the most important frameworks and offers code snippets for standard use cases.

To get the most out of this book

We recommend some knowledge of the basics and advanced CSS and JavaScript features, such as custom CSS properties or Promises. Knowing how Flexbox works is also recommended. A solid knowledge of HTML is assumed.

Software/hardware covered in the book

Operating system requirements

CSS Grid

Windows, macOS, or Linux

Flexbox

PostCSS

JavaScript

Since these technologies primarily run in the browser, they can be used on any operating system. NodeJS, used to execute some code snippets and create a web server for the accompanying project, and NPM, used to install JavaScript dependencies, are available for all major operating systems too.

To handle different versions of NodeJS, either a Docker setup or Node Version Manager (NVM) is recommended. We also require a modern browser that supports CSS Grid and offers grid tooling and a grid debugger. Having multiple browsers installed helps us to see the differences in the development tools and get used to them.

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Mastering-CSS-Grid. If there’s an update to the code, it will be updated in the GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots and diagrams used in this book. You can download it here: https://packt.link/0FCcj.

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “The total number of fr determines the size of each fr.”

A block of code is set as follows:

.container {  display: grid;   grid-template-columns: 1fr 3fr;   grid-template-rows: 1fr 4fr 1fr; }

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

header {  grid-column-end: span 2; /* Make it reach to the end of the second column */ } footer {  grid-column-end: span 2; /* Make it reach to the end of the second column */ }

Any command-line input or output is written as follows:

$ npm install$ npm run serve

Bold: Indicates a new term, an important word, or words that you see on screen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “When we open the inspector and hover over the grid container in the Elements tab, we can see what we already knew from our color experiment.”

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share your thoughts

Once you’ve read Mastering CSS Grid, we’d love to hear your thoughts! Please select https://www.amazon.in/review/create-review/error?asin=180461484X for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

Scan the QR code or visit the link below

https://packt.link/free-ebook/9781804614846

2. Submit your proof of purchase

3. That’s it! We’ll send your free PDF and other benefits to your email directly

Part 1–Working with CSS Grid

In this part, you will learn how to work with CSS Grid. You will learn the basic and advanced features of CSS Grid. In addition, from the second chapter, you will practice with a dedicated project that will accompany you throughout the book, called AwesomeAnalytics, a realistic example of a project that heavily uses CSS Grid.

This part has the following chapters:

Chapter 1, Understanding the Basic Rules and Structures for CSS GridChapter 2, Project Introduction: What We’ll Work on and First TasksChapter 3, Building Advanced Grid Layouts

1

Understanding the Basic Rules and Structures for CSS Grid

Welcome to the first chapter of this book titled Mastering CSS Grid. As the title suggests, this book helps us to become pros at this layout technique and learn about all its specialties and details. Throughout the book, we’ll work on various tasks using grid layouts in an overarching project called Awesome Analytics.

In the first chapter of this book, we will start introducing you to CSS Grid. We must first establish its basic CSS rules to understand how the grid model works. To do that, we’ll look at how grids are structured and how we can visually represent them. We’ll learn about the CSS rules used to create grid layouts, how to combine them to achieve different arrangements, and how to use shortcut rules to shorten our code.

A look at how the development tools of Google Chrome and other Chromium-based browsers visualize grids will help us understand how we can debug and understand existing grids. This chapter will not work with our overarching project just yet—we’ll first cover some theory.

So, in this chapter, we will cover the following topics:

Understanding the basic rules related to CSS GridUsing grid templatesGrid flowUnderstanding special grid-related units, keywords, and functionsUsing shortcuts

Technical requirements

For this chapter, we’ll need roughly the same things as for most chapters, as follows:

A modern browser that supports CSS Grid and offers grid debugging and a grid toolsetAn integrated development environment (IDE) or text editor, such as WebStorm, VS Code, or Vim, with HTML and CSS syntax highlightingInternet access is an advantage but not necessary

We can find several of the code examples on GitHub in this repository: https://github.com/PacktPublishing/Mastering-CSS-Grid/tree/main/chapter1.

All screenshots and examples have been made with a Chromium-based browser.

Understanding the basic rules related to CSS Grid

First, we need to know what grids are and what their purpose is. In short, grids aim to arrange items in a consistent manner. Grids provide clarity about content structure and sizing and allow us to steer where things are placed. Grids provide structure.

To achieve this understanding, we first have a look at some standard grid terminology, before creating our first CSS grid.

Defining grid terminology

We first need to establish some words we’ll use throughout the book. The following diagram will explain to us the most important terms:

Figure 1.1 – A grid and all its terms

We see many different elements here, as follows:

The grid is the whole structure. It consists of all arranged elements, the layout, and its attributes.A grid is made up of grid cells. These grid cells can have different sizes, depending on the row and column definitions we give the grid. A grid cell doesn’t necessarily have content.A grid has several grid lines. These are the lines that separate grid cells and make up the structure of the grid. They can be horizontal or vertical. In the diagram, three grid lines are marked: the two surrounding Column 1 and a single line between Row 1 and Row 2.These grid lines can become gaps. Gaps are also sometimes called gutters. Gaps are used to separate grid tracks and allow us to add white space between elements. Gaps between rows don’t have to be the same size as gaps between columns.Between two adjacent parallel grid lines, we see rows and columns of grid cells, also known as grid tracks or simply tracks. Two such tracks are marked in blue in the diagram: Row 5 and Column 1.When we place content within a grid, we speak of them as grid items. Grid items can be images, div tags, text nodes, or any other HTML element we want to place and arrange. A grid item can be seen in Row 1, Column 4 in the diagram.When we want to name specific groups of one or more cells, we speak of a grid area. Those grid areas are delimited by four grid lines and are, therefore, rectangles.

With these terms, we now have a common language to use when we talk about grids. We’ll use these terms throughout the book when defining grids.

Creating our first grid

In many ways, CSS Grid behaves like Flexbox. It needs a grid container and elements to align. In most cases, such as general page layouts or when working with teaser elements to link to additional content, we use <div> elements. Teaser elements can be built with <article> elements, too. We don’t have to, though! When working with semantic HTML, we might as well use the elements that fit best: <main>, <aside>, <header>, <footer>, <nav>, and more.

To start, let’s consider the following HTML structure. It resembles a standard Document Object Model (DOM) that we would use to structure any website and features most of the elements we would typically use when we develop a page’s layout:

<div class="container">  <header><!-- Header with a logo, navigation, etc. -->     </header>   <aside><!—Partially related things like social buttons --    ></aside>   <main><!-- Main content, headings, teasers, etc. -->     </main>   <footer><!-- Footer with contact, FAQ, etc. --></footer> </div>

We see four elements that we want to align in a grid, as follows:

A header that might contain a logo or navigationAn element that will contain content not directly related to the main page contentAn element for the actual contentA footer that displays things such as contact details, information about the company, a link to the FAQ, and similar additional controls

For ease of illustration, we will apply the following CSS upfront (the code has nothing to do with CSS Grid just yet and only serves illustration purposes):

/* 01_page_layout.html,  Micro-resetting */body { padding: 0; margin: 0; } * { box-sizing: border-box; font-size: 25px; } /* Making things visible on the page */ .container {   border: 2px solid #555;   padding: 8px;   min-height: 100vh; } header {   border: 2px solid #dd0808; /* Dark red */   background-color: #ff6666; /* Light red */ } aside {   border: 2px solid #0ba7c6; /* Dark cyan */   background-color: #74ddf2; /* Light cyan */ } main {   border: 2px solid #6f09e5; /* Dark purple */   background-color: #b880f7; /* Light purple */ } footer {   border: 2px solid #c4be0d; /* Dark yellow */   background-color: #f7f380; /* Light yellow */ }

This CSS code will color our containers and ensure we can track which element goes where. When loaded up in a browser, this results in four colored stripes along the screen. That’s what we expected. After all, our DOM does not have any content.

Things get interesting, though, when we add the following CSS code:

.container {  display: grid; /* Marks this class as a grid container */ }

When reloading, we see that CSS Grid has evenly distributed the four containers vertically. Since the outer <div> element has a fixed height, CSS will calculate the height of every element and rescale it to fit. Since we have not yet defined anything other than This is a grid, each element takes up the same amount of space:

Figure 1.2 – Our HTML is styled and displayed as a grid

CSS Grid has entirely taken over the placing and sizing of statically and relatively positioned elements within the grid. This, in turn, means that any other inline positioning method does not apply anymore. Any use of display: inline-block, display: table-cell, float, or vertical-align will have no effect. However, we can still use position: fixed, position: absolute, or position: sticky because the elements are not static anymore. Elements that have position: relative; attached to them can be moved around and are still affected by the grid.

There’s also the possibility to define an inline grid by using display: inline-grid;. The main difference is that the grid container behaves like an inline container instead of a block container. Therefore, we now know that display: grid defines a grid that behaves like a block element.

Let’s remove the colors briefly and see how the browser development tools indicate that we use a grid. Usually, Chrome shows grids with dashed lines. When we open the inspector and hover over the grid container in the Elements tab, we can see what we already knew from our color experiment. We can also click on the grid button that appears in the inspector to turn on grid debugging, which will show us the grid lines.

In the following screenshot, we can see the full grid representation in Chrome’s development tools:

Figure 1.3 – Chrome’s inspector showing us the different grid slots

Just as in the color experiment we did before, we see four grid rows, indicated by purple dashed lines. These lines also indicate the grid lines and would become larger once we introduce gaps. The blue areas we see are our grid cells. Currently, they don’t contain any grid items. The green border around the grid is our padding. It’s not related to the grid.

Arranging grid elements

So far, CSS Grid has taken care of arranging things for us—in our example, it automatically created four rows because there were four elements, spaced them evenly, and placed them in the same order as they appeared in the DOM.

However, often, we don’t want this, especially when wanting responsive layouts. For example, on a mobile, social media buttons might move to the bottom of the page and become sticky elements, whereas on a desktop they should stay in one place, such as the sidebar.

To be able to move elements, we first need to state the number of grid rows and grid columns explicitly. We achieve this by using the grid-template-rows and grid-template-columns rules, which go into the container element and will pre-create a grid structure for us. We specify the number of grid columns and rows by providing their size, separated by spaces. The size may vary from row to row and column to column.

The total number of grid cells may be larger than the total amount of elements we’d like to arrange. We can, for example, define a grid with three rows and three columns and only arrange five items within it—a case that’s common in galleries or news websites. The remaining grid cells remain empty.

For the time being, let’s work with 1fr. fr is a unit that has been introduced to CSS with CSS Grid and works exclusively with grids. 1fr essentially means: Take one unit of free space for this grid element. We will discuss the fr unit later in this chapter. So, if we used it for grid rows, this means taking one unit of free space for this grid row. The same applies to columns too.

Let’s change our example to a 2x3 grid of evenly spaced grid elements by applying the following CSS code to the container class:

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

As we can see, we used 1fr twice in grid-template-columns, resulting in two equally sized columns, and three times in grid-template-rows, resulting in three equally sized rows. When inspected, Chrome shows us that it has now created a grid structure, as indicated in the following screenshot:

Figure 1.4 – Chrome’s inspector showing us our 2x3 grid

CSS Grid assigns integers to all grid lines for us to use as coordinates. These integers increase from left to right and top to bottom, starting at 1. When we think of the grid as a coordinate system, its origin is in the top-left corner. This allows us to place grid items starting from the top left to the bottom right.

However, CSS Grid offers a second origin that lets us place items from the bottom-right to the top-left corner. It does so by also assigning negative integers to the same grid lines, starting at the bottom-right corner with -1.

Our grid so far would receive the numbers illustrated here:

Figure 1.5 – Grid line numbering

Currently, all columns are the same size. If we want one column twice the size of the other, we increase the value of that column to 2fr. For example, if we wish to have a 1/4 sidebar and 3/4 main content slot, we adjust the grid-template-column rule to 1fr 3fr. Then, if wanted to have a 1/6 header, 1/6 footer, and the other 2/3 (4/6 in a six-column layout) for the main content, we would use the grid-template-rows: 1fr 4fr 1fr rule.

We see that the size of the grid rows and columns depends on the total number of free space units. If we think of a grid as 100% wide and 100% tall, we can calculate the size of each row and column as percentages. For example, in a layout with four columns of size 1fr, each column takes up 25% of the space.

In a two-column layout with sizes 1fr and 3fr, however, the total number of free space units is 4, resulting in 1fr being 25% wide and 3fr equaling 75% width. The total number of fr units determines the size of each fr unit.

Let’s adjust our example to this new layout:

.container {  display: grid;   grid-template-columns: 1fr 3fr;   grid-template-rows: 1fr 4fr 1fr; }

This won’t affect the assigned numbers (they just stay the same), but we can see that this has the desired effect when inspecting, as illustrated in the following screenshot:

Figure 1.6 – Chrome’s inspector shows us our adjusted 2x3 grid

By re-applying the colors, we can now see the default arrangement for this grid. By default, CSS Grid fills grid elements from left to right, top to bottom. This grid resembles a painting by Piet Mondrian and is not exactly what we’d like:

Figure 1.7 – Our accidental neoplasticism painting, using CSS on HTML

But we still have not explicitly arranged the elements yet. For that, we use four different CSS rules: grid-column-start, grid-column-end, grid-row-start, and grid-row-end. We apply these to the elements we want to position—so, in our case, header (marked red), footer (marked yellow), aside (marked cyan), and main (marked purple).

By default, grid-row-start, grid-row-end, grid-column-start, and grid-column-end will have the auto value, meaning that CSS Grid will figure out the beginning row and column itself, again with the left-to-right, top-to-bottom method. Most of the time, this is enough. We can, however, define where to place any element explicitly.

Looking at the grid outline in Figure 1.6, we notice that the header and footer both have to span two columns. We achieve this with the span keyword for grid-column-end and grid-row-end. span tells the browser to enlarge the element until it encounters a grid cell with that name or for the amount specified. (But wait—grid cells can have names? Yes, they can. We’ll have a look at this a bit later in this chapter.)

So, grid-column-end: span 2; means enlarge the element to a width of two columns, and grid-column-end: span something; means enlarge the element to the gap named “something” (we will have a look at gap names later on too). If the element already starts at the second column, this will not do much. However, if it begins in the first column, it will fill two adjacent grid cells.

Let’s place the header and footer first since they work very similarly:

header {  grid-column-end: span 2; /* Make it reach to the end of     the second column */ } footer {   grid-column-end: span 2; /* Make it reach to the end of     the second column */ }

Let’s see if this does what we want. And indeed, it does. The default placing of the main and aside grid elements already makes them appear in the place we want them to. Since the header and the footer elements both take up two grid cells each, we’re left with two remaining grid cells for the main and aside elements.

These grid cells are occupied by the aside and main elements in the order of appearance in the HTML code:

Figure 1.8 – The header, sidebar, content, and footer elements arranged

Adding some breathing room (or gaps)

Right now, all the elements are aligned snuggly. However, we don’t always want this. Especially for