Class 39 | CSS Flexbox and Grid Layout

CSS Flexbox and Grid Layout
CSS Flexbox and Grid Layout

CSS Flexbox is a layout mode that allows you to arrange elements in a flexible manner in one dimension, either horizontally or vertically. CSS Grid Layout, on the other hand, is a two-dimensional layout system that allows you to arrange elements in rows and columns.

Let’s take a look at some examples of both CSS Flexbox and Grid Layout:

CSS Flexbox

Example 1: Basic Flexbox Layout

HTML:

<div class="container">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
</div>

CSS:

.container {
  display: flex;
}

.item {
  width: 100px;
  height: 100px;
  background-color: red;
  margin: 10px;
}

In this example, we have a container with three items inside it. By setting the display property of the container to flex, we’re telling it to use Flexbox layout. The item class sets the width, height, and background color of each item. The margin property adds some space between the items.

Example 2: Centering Items Horizontally and Vertically

HTML:

<div class="container">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
</div>

CSS:

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.item {
  width: 100px;
  height: 100px;
  background-color: red;
  margin: 10px;
}

In this example, we’re centering the items both horizontally and vertically inside the container. The justify-content property centers the items horizontally, and the align-items property centers them vertically. We’ve also set a fixed height for the container to make the centering more visible.

CSS Grid Layout

Example 1: Basic Grid Layout

HTML:

<div class="container">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>
  <div class="item">6</div>
</div>

CSS:

.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(2, 100px);
  gap: 10px;
}

.item {
  background-color: red;
  padding: 20px;
}

In this example, we have a container with six items inside it. By setting the display property of the container to grid, we’re telling it to use Grid Layout. The grid-template-columns property specifies that the grid should have three columns, each with a width of 1 fraction unit (1fr). The grid-template-rows property specifies that the grid should have two rows, each with a height of 100 pixels. The gap property adds some space between the items.

Example 2: Spanning Rows and Columns

HTML:

<div class="container">
  <div class="item item1">1</div>
  <div class="item item2">2</div>
  <div class="item item3">

Leave a Comment