Sub topic 1
Creating a grid container
Prerequisites
This chapter assumes you already know the following:
- Basic HTML structure: elements, nesting, and parent and child relationships.
- CSS selectors and the box model: content, padding, border, and margin.
- The
displayproperty and normal document flow, including the difference between block and inline boxes. - CSS length units such as
px,%, andrem.
You do not need to know any Grid properties yet. This chapter covers the first step, which is turning an element into a grid container. Later chapters cover defining tracks, placing items, and sizing.
What a grid container is
CSS Grid is a layout system for arranging content in rows and columns at the same time. Flexbox lays items out along one axis. Grid controls both axes together.
A grid starts with one declaration:
.container {
display: grid;
}The element matching .container becomes a grid container. Its direct children become grid items. Only direct children are affected. Grandchildren are laid out normally inside their parent item, unless you make that item a grid too, which a later chapter covers.
A few terms you will use throughout the tutorial:
- Grid container: the element with
display: gridordisplay: inline-grid. - Grid item: a direct child of the grid container.
- Track: a single row or a single column of the grid.
- Cell: the space where one row and one column cross.
- Line: the dividing line between tracks, including the outer edges.
- Area: a rectangular region made of one or more cells.
A first example
Here is some HTML with a container and four items:
<div class="container">
<div class="item">One</div>
<div class="item">Two</div>
<div class="item">Three</div>
<div class="item">Four</div>
</div>Apply only display: grid and some visual styling so you can see the boxes:
.container {
display: grid;
border: 2px solid #334;
}
.item {
background: #cde;
border: 1px solid #667;
padding: 1rem;
}The result looks almost the same as normal block layout. The four items are stacked vertically, each stretching the full width of the container. This surprises many learners. The reason is that you have not defined any columns yet. A grid with no column definition has exactly one column, and it fills the container width. Each item goes into its own automatically created row.
So display: grid alone creates the grid structure. It does not create a visible multi-column layout until you define tracks.
Adding columns and rows
The next step is to describe the tracks. The properties grid-template-columns and grid-template-rows take a list of track sizes, separated by spaces.
.container {
display: grid;
grid-template-columns: 200px 1fr 1fr;
grid-template-rows: auto auto;
gap: 16px;
}This defines three columns. The first is fixed at 200px. The other two share the remaining space equally, because 1fr means one share of the free space. It also defines two rows sized to fit their content, with 16px between tracks. With four items, the first three fill the first row and the fourth starts the second row.
Later chapters cover fr, gap, and track sizing in detail. For now, the point is that the container defines the tracks, and the items flow into the cells.
Block-level versus inline grid containers
Two values create a grid container, and they differ in how the container itself behaves in its parent's flow.
| Value | Container behaves like | Width by default |
|---|---|---|
| `display: grid` | A block-level box | Fills the available width |
| `display: inline-grid` | An inline-level box | Shrinks to fit its content |
Both values create the same internal grid layout for the children. The difference is only in how the container sits among its siblings. With inline-grid, the container can sit on the same line as text or other inline boxes.
.badge-group {
display: inline-grid;
grid-template-columns: auto auto;
gap: 4px;
}In practice, display: grid is far more common. Use inline-grid when the whole grid needs to flow inline with surrounding text.
What changes for the children
Turning on a grid changes how the container's children behave. Knowing these changes avoids a lot of confusion.
- Float and clear stop working on grid items. A floated child of a grid container ignores the float.
vertical-alignhas no effect on grid items. Use the alignment properties instead.- Margins do not collapse. Margins between grid items and the container never collapse, unlike in normal block flow.
- Items become "blockified". A child that was
display: inline, such as aspan, is treated as a block-level box once it is a grid item. - Text directly inside the container is wrapped. Loose text becomes an anonymous grid item, which takes a cell of its own. You cannot target it with a selector.
- Items stretch by default. An item with no explicit width or height fills its cell in both directions.
A related gotcha: ::first-line and ::first-letter do not apply to the container itself, because a grid container does not form a block of inline text.
Direction and writing mode
Grid follows the writing mode of the document. In a left-to-right language such as English, columns are laid out starting at the left. In a right-to-left language, such as Arabic or Hebrew, the first column is on the right. Rows start at the top in horizontal writing modes.
This means grid placement is written in terms of the start and end of the flow, not physical left and right. Your layout adapts when you set dir="rtl" or a different writing-mode, with no extra rules.
How the container sizes itself
The container's own size and the track sizes are separate concerns.
- A block-level grid container takes the full available width, like any block element. Its height comes from its content unless you set one.
- If the container is taller than the tracks need, the extra space does not automatically stretch the rows. Rows sized with
autodo absorb leftover space by default, but fixed-size rows do not. - If you give the container a fixed width smaller than the sum of its fixed-size tracks, the tracks overflow the container.
This example shows the overflow case:
.container {
display: grid;
width: 300px;
grid-template-columns: 200px 200px;
}The two columns need 400px, but the container is 300px wide. The second column spills out past the container's right edge. It is not clipped and it does not shrink. Flexible units, covered in the next chapters, avoid this problem.
Common errors
- Setting
display: gridon the wrong element. The styles must be on the parent of the items you want to arrange, not on the items themselves. - Expecting grandchildren to join the grid. Only direct children are grid items. Nested content stays inside its parent item.
- Expecting columns from
display: gridalone. Withoutgrid-template-columns, you get a single column. - Using floats or
vertical-alignon items. These are ignored. Switch to grid placement and alignment properties. - Forgetting that
inline-gridshrinks. If a container looks too narrow, check whether you usedinline-gridby accident.
Checking your grid in the browser
Browser developer tools can show the grid so you do not have to guess. In Chrome, Edge, and Firefox, an element with display: grid gets a small "grid" badge in the Elements (or Inspector) panel. Clicking it overlays the lines and track numbers on the page. Use this overlay whenever a layout does not match what you expect.
Summary
display: gridturns an element into a block-level grid container.display: inline-gridmakes an inline-level one.- Direct children become grid items, including anonymous items made from loose text and pseudo-elements.
- Without track definitions, the grid has a single column and automatically created rows.
grid-template-columnsandgrid-template-rowsdefine the tracks that items flow into.- Floats,
vertical-align, and margin collapsing do not apply to grid items.
Exercise
You write .list { display: grid; } for a div with five p children, and the paragraphs are still stacked in one column. Why, and what is the smallest change that places them in three columns?
Show answer
A grid with no column definition has a single column, so the items go into five automatically created rows. Add grid-template-columns: repeat(3, 1fr); (or 1fr 1fr 1fr) to .list. The first three paragraphs then fill the first row and the remaining two start the second row.
Exercise
A container has display: grid and contains a div, and inside that div are three span elements. Which elements are grid items, and what happens if you want the spans to be arranged on the same grid?
Show answer
Only the div is a grid item, because only direct children of the container become items. The spans are laid out normally inside the div. To arrange them in a grid, make the div a grid container itself with display: grid, creating a nested grid, or use subgrid, which a later chapter covers.