Skip to content

CSS 垂直居中

想要实现的效果

基础代码

html
<div class="out">
    <div class="in"></div>
</div>
css
.out {
    width: 200px;
    height: 200px;
    background-color: #34537c;
}
.in {
    width: 100px;
    height: 100px;
    background-color: gold;
}

使用 flex 布局

css
.out {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
}

使用 grid 布局

css
.out {
    display: grid;
    place-items: center;
}

使用绝对定位

css
.out {
    position: relative;  
}
.in {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

使用盒模型

margin: auto; 可以水平居中,table-cell 可以垂直居中。

css
.out {
    display: table-cell;
    vertical-align: middle;
}
.in {
    margin: auto;
}

文字居中:使用 line-height

line-height 设置为和 height 相同的值即可垂直居中,然后 text-align: center; 可以水平居中。

适用于固定高度的情况。

文字垂直居中
html
<div class="text-center">
    文字垂直居中
</div>
css
.text-center {
    width: 300px;
    height: 200px;
    background-color: #34537c;
    color: white;
    line-height: 200px;
    text-align: center;
}
评论区
评论区空空如也
发送评论
名字
0 / 20
邮箱
0 / 100
评论内容
0 / 140
由于是非实名评论,所以不提供删除功能。如果你需要删除你发送的评论,或者是其他人的评论对你造成了困扰,请 发邮件给我 。同时评论区会使用 AI + 人工的方式进行审核,以达到合规要求。

© thebestxt.cc
辽ICP备16009524号-8
本站所有文章版权所有,转载请注明出处