Home  >  Article  >  Web Front-end  >  How to center a div?

How to center a div?

WBOY
WBOYOriginal
2024-07-17 13:52:07454browse

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;
}
<div class="container">
    <div class="centered-div">Centered Content</div>
</div>

2. Centering with Grid

CSS Grid can also center content:

.container {
    display: grid;
    place-items: center;
    height: 100vh;
}
<div class="container">
    <div class="centered-div">Centered Content</div>
</div>

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%);
}
<div class="container">
    <div class="centered-div">Centered Content</div>
</div>

4. Centering with Margin Auto

For simple horizontal centering, use margin: auto:

.centered-div {
    width: 50%;
    margin: 0 auto;
}
<div class="centered-div">Centered Content</div>

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;
}
<div class="container">
    <div class="centered-div">Centered Content</div>
</div>

The above is the detailed content of How to center a div?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn