DEV Community

Mohd Anas
Mohd Anas

Posted on

1 1 1 1

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.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more