卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章66019本站已运行421

如何让div居中?

如何让div居中?

如何在 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>
卓越飞翔博客
上一篇: Typescript 编程编年史:拥有最多糖果的孩子
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏