」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何讓div居中?

如何讓div居中?

發佈於2024-11-12
瀏覽:299

How to center a div?

如何在 CSS 中將 Div 居中

div居中是最不可能的事

1. 使用 Flexbox 居中

Flexbox 是一種垂直和水平居中內容的現代方式:

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

2. 網格居中

CSS Grid也可以居中內容:

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

3. 絕對定位居中

您可以使用絕對定位將 div 置中:

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

4. 使用 Margin Auto 居中

對於簡單的水平居中,使用 margin: auto:

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

5. 使用 Margin Auto 居中

對於內聯或內聯塊元素:

.container {
    text-align: center;
    line-height: 100vh;
}
.centered-div {
    display: inline-block;
    vertical-align: middle;
    line-height: normal;
}
Centered Content
版本聲明 本文轉載於:https://dev.to/mb337/how-to-center-a-div-3c2a?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3