"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 > How to center a div?

How to center a div?

Published on 2024-11-12
Browse:743

How to center a div?

How to Center a Div in CSS

Centering a div is the most impossible thing

1. Centering with Flexbox

Flexbox is a modern way to center content both vertically and horizontally:

.container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}
Centered Content

2. Centering with Grid

CSS Grid can also center content:

.container {
    display: grid;
    place-items: center;
    height: 100vh;
}
Centered Content

3. Centering with Absolute Positioning

You can center a div using absolute positioning:

.container {
    position: relative;
    height: 100vh;
}
.centered-div {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
Centered Content

4. Centering with Margin Auto

For simple horizontal centering, use margin: auto:

.centered-div {
    width: 50%;
    margin: 0 auto;
}
Centered Content

5. Centering with Margin Auto

For inline or inline-block elements:

.container {
    text-align: center;
    line-height: 100vh;
}
.centered-div {
    display: inline-block;
    vertical-align: middle;
    line-height: normal;
}
Centered Content
Release Statement This article is reproduced at: https://dev.to/mb337/how-to-center-a-div-3c2a?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