DEV Community

hahaxo
hahaxo

Posted on

2024:How to Center a Div in CSS

Flexbox:

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

Grid

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

Flex Margin

.container {
  display: flex;
  height: 300px;
}
.centered-div {
  margin: auto;
}
Enter fullscreen mode Exit fullscreen mode

Absolute Positioning

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

Margin Auto

.container {
  height: 300px;
}
.centered-div {
  width: 200px;
  margin: 0 auto;
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}
Enter fullscreen mode Exit fullscreen mode

Grid Template

.container {
  display: grid;
  grid-template-columns: 1fr auto 1fr;
  grid-template-rows: 1fr auto 1fr;
  height: 300px;
}
.centered-div {
  grid-column: 2;
  grid-row: 2;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
ddfridley profile image
David

In my experience they height is not known and is defined by the child and that makes it a challenge to center.