Professional ways to center a div

mdanassaif

Mohd Anas

Posted on April 3, 2023

Professional ways to center a div

Image description

There are several ways to center an div in CSS. Here are some professional ways:

1.Using Flexbox:

.container {
  display: flex;
  justify-content: center;
  align-items: center;
}
Enter fullscreen mode Exit fullscreen mode

2. Using Grid:

.container {
  display: grid;
  place-items: center;
}
Enter fullscreen mode Exit fullscreen mode

3. Using Absolute Positioning:

.container {
  position: relative;
}
.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
Enter fullscreen mode Exit fullscreen mode

4. Using Text-align Property:

.container {
  text-align: center;
}
Enter fullscreen mode Exit fullscreen mode

5. Using Margin Property:

.container {
  width: 50%; /* or any other fixed width */
  margin: 0 auto;
}
Enter fullscreen mode Exit fullscreen mode

6. Using Table-cell Display:

.container {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}
Enter fullscreen mode Exit fullscreen mode

7. Using Line-height Property:

.container {
  height: 100px; /* or any other fixed height */
  line-height: 100px;
  text-align: center;
}
Enter fullscreen mode Exit fullscreen mode

I hope the methods provided for centering a div in CSS are useful to you in achieving your desired layout for your project.

πŸ’– πŸ’ͺ πŸ™… 🚩
mdanassaif
Mohd Anas

Posted on April 3, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related