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

How to center a div?

WBOY
Release: 2024-07-17 13:52:07
Original
664 people have browsed it

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

2. Centering with Grid

CSS Grid can also center content:

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

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

4. Centering with Margin Auto

For simple horizontal centering, use margin: auto:

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

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

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!

source:dev.to
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template