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 flexibly, horizontally, or vertically. On the other hand, CSS Grid Layout is a two-dimensional layout system that arranges 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 For the property of the container, we’re telling it to use the Flexbox layout. The item class sees the item’s width, height, and background color. The margin of the 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 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, 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

Your email address will not be published. Required fields are marked *

Scroll to Top