"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > ow to Center a Div in CSS

ow to Center a Div in CSS

Published on 2024-11-08
Browse:258

ow to Center a Div in CSS

Flexbox:

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

Grid

.container {
  display: grid;
  place-items: center;
  height: 300px;
}

Flex Margin

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

Absolute Positioning

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

Margin Auto

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

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;
}
Release Statement This article is reproduced at: https://dev.to/hahaxo/2024how-to-center-a-div-in-css-2hjj?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3