css

2024:How to Center a Div in CSS

hahaxo

hahaxo

Posted on September 20, 2024

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
💖 💪 🙅 🚩
hahaxo
hahaxo

Posted on September 20, 2024

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

Sign up to receive the latest update from our blog.

Related