DEV Community

Code WithDhanian
Code WithDhanian

Posted on

7 Ways to Center a Div

Image description

Centering a div is a fundamental CSS skill. Whether horizontal, vertical, or both, here are seven ways to achieve it effectively:

1. Using Flexbox

Flexbox simplifies centering with justify-content and align-items.

.parent {
  display: flex;
  justify-content: center; /* Horizontal */
  align-items: center;    /* Vertical */
  height: 100vh;          /* Full height */
}
Enter fullscreen mode Exit fullscreen mode

2. Using Grid Layout

CSS Grid provides a quick way to center elements with place-items.

.parent {
  display: grid;
  place-items: center; /* Centers horizontally and vertically */
  height: 100vh;
}
Enter fullscreen mode Exit fullscreen mode

3. Using margin: auto

This method is great for horizontally centering block elements.

.child {
  margin: auto;
  width: 200px;
  height: 100px;
}
Enter fullscreen mode Exit fullscreen mode

For vertical centering, combine it with position and transform.

4. Using position and transform

This technique is ideal for absolute positioning.

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

5. Using Text Alignment

For inline or inline-block elements, text-align centers them horizontally.

.parent {
  text-align: center;
}

.child {
  display: inline-block;
}
Enter fullscreen mode Exit fullscreen mode

6. Using Table Display

This method uses display: table and display: table-cell for centering.

.parent {
  display: table;
  height: 100vh;
}

.child {
  display: table-cell;
  text-align: center; /* Horizontal */
  vertical-align: middle; /* Vertical */
}
Enter fullscreen mode Exit fullscreen mode

7. Using line-height for Text

This approach works well for centering single-line text within a div.

.child {
  height: 100px;
  line-height: 100px; /* Matches height */
  text-align: center;
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

These seven methods cover the most common use cases for centering a div. Flexbox and Grid are ideal for modern layouts, while older methods like position and margin are useful for specific scenarios.

Which method do you use most often?

Buymecoffee at https://ko-fi.com/codewithdhanian

Top comments (0)