如何让div居中?-css教程

首页 2024-07-11 22:53:06

如何在 css 中将 div 居中

使div居中是最不可能的

1. 使用 flexbox 居中

flexbox 它是一种垂直和水平内容的现代方式:

.container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}
<div class="container">
    <div class="centered-div">centered content</div>
</div>
2. 网格居中

css grid 还可以居中内容:

.container {
    display: grid;
    place-items: center;
    height: 100vh;
}
<div class="container">
    <div class="centered-div">centered content</div>
</div>
3. 绝对定位在中间

您可以使用绝对定位 div 居中:

.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. 使用 margin auto 居中

对简单的水平居中,请使用 margin: auto:

.centered-div {
    width: 50%;
    margin: 0 auto;
}
<div class="centered-div">centered content</div>
5. 使用 margin auto 居中

内联元素或内联元素:

.container {
    text-align: center;
    line-height: 100vh; /* full viewport height for vertical centering */
}
.centered-div {
    display: inline-block;
    vertical-align: middle;
    line-height: normal;
}
<div class="container">
    <div class="centered-div">centered content</div>
</div>

以上就是如何让div居中?详情请关注其他相关文章!


p
MySQL连接就这么简单!本地远程、编程语言连接方法一网打尽
还在为MySQL日期计算头疼?这份加一天操作指南能解决90%问题
MySQL日志到底在哪里?Linux/Windows/macOS全平台查找方法在此
MySQL数据库管理工具全景评测:从Workbench到DBeaver的技术选型指南
MySQL密码忘了怎么办?这份重置指南能救急,Windows/Linux/Mac都适用
你的MySQL为什么经常卡死?可能是锁表在作怪!快速排查方法在此
MySQL单表卡爆怎么办?从策略到实战,一文掌握「分表」救命技巧
清空MySQL数据表千万别用错!DELETE和TRUNCATE这个区别可能导致重大事故
你的MySQL中文排序一团糟?记住这几点,轻松实现准确拼音排序!
别再混淆Hive和MySQL了!读懂它们的天壤之别,才算摸到大数据的门道