Trusted answers to developer questions

How to insert grid layout in CSS

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

CSS Grid is a two-dimensional layout system, with rows and columns, used to place and position content on webpages in a more natural way than tables, without having to use floats and positioning properties.

A grid element consists of a parent element, with one or more children elements. The children inherit the properties from the parent, can position themselves accordingly and even overlap.

The following illustration introduces important grid terminology:

Parent Element: Grid Container
1 of 9

Example

The grid below contains four columns and three rows. Item 1 and Item 6 have been manually positioned inside the grid.

Line 2: An HTML element acts as a grid container when its display property is set to grid or inline-grid.

Line 3,4: grid-template-rows and grid-template-columns properties define how many rows and columns the grid has. The list of values separated by space defines the height and width for each row and column respectively.

Line 5: grid-gap property defines the spacing between rows and columns. grid-row-gap and grid-column-gap properties also exist to define the spacing separately for rows and columns.

Line 10: Each div inside the grid-container would have this style applied to it. Here grid-container is the parent element.

Line 17-20: grid-row-start and grid-row-end define how many rows the grid-item spans.

Line 22-24: grid-column defines how many columns a grid item spans. It can also be defined using grid-column-start and grid-column-end properties, as used for rows in the last step. 3/5 means that the element includes the 3rd line and ends right before the 5th line.

We deal with the parent element grid-container in Lines 1-8. Since each div element inside the grid-container acts like a child, Line 10-15, applies the style to children elements. Then the span of certain children elements is defined, inside the parent Line 17-24.

RELATED TAGS

css
grid
table
flexbox
grid layout
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?