Categories
Uncategorized

Divide CSS3 Grid into fixed equal columns

Defining a fixed set of equal width items for each row in a grid can be done using the grid-template-columns property in CSS3.

grid-template-columns: repeat(numberOfColumns, widthOfEachColumn);

You can implement this in any of the following 3 ways.

grid-template-columns: repeat(3, 200px);
grid-template-columns: repeat(3, 1fr);
grid-template-columns: repeat(3, 25%);

 Note that here fr is the fractional unit, which represents a fraction of the leftover space in the grid container.

Demo

index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>CSS3 - Grid Demo</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <div class="grid-container">
    <div class="grid-item">1</div>
    <div class="grid-item">2</div>
    <div class="grid-item">3</div>
    <div class="grid-item">4</div>
    <div class="grid-item">5</div>
    <div class="grid-item">6</div>
    <div class="grid-item">7</div>
    <div class="grid-item">8</div>
  </div>
</body>
</html>

style.css

.grid-container {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  background-color: lightblue;
  padding: 10px;
}

.grid-item {
  background-color: lightgreen;
  border: 1px solid darkblue;
  padding: 20px;
  font-size: 30px;
  text-align: center;
}