CSS实现水平垂直居中

方法一:父元素: display: flex; + 子元素:margin: auto;
  1. 适用于有宽高的盒子

    <div class="big-box">
        <div class="inner-box"></div>
    </div>
    
    .big-box {
        width: 400px;
        height: 400px;
        background-color: darkseagreen;
        display: flex;
    }
    
    .inner-box {
        width: 200px;
        height: 200px;
        background-color: rgb(243, 236, 132);
        margin: auto;
    }
    

在这里插入图片描述

  1. 适用于文字内容所在的元素没有宽高

    .inner-box {
        width: 200px;
        height: 200px;
        background-color: rgb(243, 236, 132);
        margin: auto;
        display: flex;
    }
    p {
        color: #333;
        margin: auto;
    }
    

在这里插入图片描述

如果给文字内容所在p元素设置宽高,使用这个方法,文字就不居中了

.inner-box {
    width: 200px;
    height: 200px;
    background-color: rgb(243, 236, 132);
    margin: auto;
    display: flex;
}
p {
    color: #333;
    margin: auto;
    width: 200px;
    height: 100px;
}

inner-box 有宽高,显示如下图:

在这里插入图片描述

如果给文字内容所在p元素设置宽高,使用这个方法,文字就不居中了

.inner-box {
    /* width: 200px;
    height: 200px; */
    background-color: rgb(243, 236, 132);
    margin: auto;
    display: flex;
}
 p {
    color: #333;
    margin: auto;
    width: 200px;
    height: 200px;
}

inner-box 没有宽高,显示如下图:

在这里插入图片描述

方法二:使用Flexbox(弹性布局)
<div class="big-box">
    <div class="inner-box">
        你好
    </div>
</div>
.container {
    height: 400px;
    background-color: #bfc;
    display: flex;
    justify-content: center; /* 水平居中 */
    align-items: center; /* 垂直居中 */
}

在这里插入图片描述

方法三:父元素:text-align: center;line-height: *;

适用于内联元素,如文本或行内块元素。(文字内容所在盒子没有设置宽高的情况下。)

<div class="big-box">
    <div class="inner-box">
        你好
    </div>
</div>
.big-box {
    width: 400px;
    height: 400px;
    background-color: #bfc;
    text-align: center;
    line-height: 400px;
}

如果文字内容所在盒子有宽高,则不水平居中对齐。

.inner-box {
    width: 100px;
    height: 100px;
}

在这里插入图片描述

方法四:使用Grid(网格布局)
.big-box  {
    display: grid;
    place-items: center; /* 同时实现水平和垂直居中 */
    width: 400px;
    height: 400px;
    background-color: #bfc;
}
方法五:使用绝对定位
.big-box  {
    position: relative;
    width: 400px;
    height: 400px;
    background-color: #bfc;
}

.inner-box {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%); /* 负的50%来实现水平和垂直居中 */
}
方法六:使用表格布局
.big-box {
    display: table;
    width: 400px;
    height: 400px;
    background-color: #bfc;
}

.inner-box {
    display: table-cell;
    text-align: center; /* 水平居中 */
    vertical-align: middle; /* 垂直居中 */
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值