CSS grid (Grid Layout with Example)

The CSS grid is used to design or layout a web page based on grid layout model. In grid layout model, everything is separated in the form of rows and columns. For example:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      .container {display: grid; gap: 2px; background-color: chocolate; color: whitesmoke;
         grid-template-areas: 'head head head' 'nav main oth' 'foot foot foot';}
      .container > div {background-color: maroon; padding: 10px; text-align: center;}
      #header {grid-area: head;}
      #menu {grid-area: nav;}
      #content {grid-area: main;}
      #other {grid-area: oth;}
      #footer {grid-area: foot;}
   </style>
</head>
<body>

   <div class="container">
      <div id="header">HEADER</div>
      <div id="menu">MENU</div>
      <div id="content">CONTENT</div>
      <div id="other">OTHER</div>
      <div id="footer">FOOTER</div>
   </div>
   
</body>
</html>
Output
CONTENT
OTHER

This is just a demo example to show the sample of grid layout model. You'll learn all about layout designing using grid layout model, one by one, starting from next article/tutorial.

CSS Grid Layout Model

css grid layout

CSS Grid Elements

Grid elements are those elements that are the direct child of grid container or an element whose display property is set to grid or inline-grid. For example:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      .container {display: grid; gap: 4px; background-color: peru; color: whitesmoke;
         grid-template-columns: auto auto auto;}
      .container > div {background-color: maroon; padding: 10px; text-align: center;}
   </style>
</head>
<body>

   <div class="container">
      <div>A</div>
      <div>B</div>
      <div>
         <div>C1</div>
         <div>C2</div>
         <div>C3</div>
      </div>
      <div>D</div>
      <div>E</div>
      <div>F</div>
   </div>
   
</body>
</html>
Output
A
B
C1
C2
C3
D
E
F

In above example, because the DIV with class container is set to grid using the following CSS code:

.container {display: grid;}

And this DIV with container class has other DIVs inside it. Those all DIVs are its child elements. Therefore the direct child becomes the grid items of this DIV.

Note - In CSS, a grid layout consists of a parent with one or multiple child elements.

Note - I've described grid Vs inline-grid and flex Vs grid in its separate tutorial.

What is CSS Grid Used For ?

CSS grid is used to layout a/some part(s) of a web page or the whole web page in the form of rows and columns.

List of All CSS Grid Properties

CSS Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!