浅记录一下CSS水平垂直居中的几种方法

方法实在太多太杂了,浅记录一下垂直居中的几大方法

1.第一种是个人比较喜欢的,运用flex布局,兼容性也较强,没啥技巧,记住就完事了。

display: flex;

flex-direction: row;   /*设置主轴方向为水平,即横向水平*/

align-items: center;  /*设置侧轴子元素的排列方式为居中对齐*/

2.第二种比较简单,原理就是:块级元素在水平方向上具有满屏特性,表现为水平方向上占满整个父容器的宽度,所以,当水平方向上padding、border,width都是定值时,margin左右外边距设置为auto,默认会由margin左右平分剩余空间。

margin:0 auto;/*块元素水平居中*/

height:200px;

line-height:200px;/*把行高line-height和高度height设置为一样,可以实现文本元素的垂直对齐,*/

适用于文本、行内块元素、行内元素的垂直居中,块元素的垂直居中不适用

3.第三种就是定位了

给父元素设置相对定位,子元素绝对定位,即我们常说的子绝父相;

利用绝对定位将四个定位属性的值都设置为0,top: 0; left: 0;bottom: 0;right: 0;如果子级没有设置宽高,则会被拉开到和父级一样宽高,这里子元素设置了宽高,所以宽高会按照我们的设置来显示,但是实际上子级的虚拟占位已经撑满了整个父级,这时候再给它一个margin: auto它就可以上下左右都居中了。

<style>
    .father {
        width: 400px;
        height: 100px;
        background-color: black;
        position: relative;
    }

    .son {
        width: 100px;
        height: 100px; 
        position: absolute;
        top: 0;
        left: 0;
        bottom: 0;
        right: 0;
        margin: auto;
    }
</style>
<body>
<div class="father">
    <div class="son">
        水平垂直居中
    </div>
</div>
</body>

4.第四种也是定位,与transform结合使用

原理就是:

设置父元素为相对定位, 子元素绝对定位,

先让元素向右和向下移动父元素的50%,在向上和向右移动自身的50%,从而移动到了父元素水平垂直方向的中间位置。

<style>
    .father {
        width: 400px;
        height: 400px;
        background-color: black;
        position: relative;
    }

    .son {
        width: 100px;
        height: 100px;
        position: absolute;
        background-color: white;
        top:50%;  //向下移动父元素的50%
        left:50%; //移动右父元素的50%
        transform:translate(-50%, -50%); //子元素向左,向上移动自身50%实现水平垂直居中
    }
</style>
<body>
<div class="father">
    <div class="son">
        水平垂直居中
    </div>
</div>
</body>

5.最后补充一个table布局吧

父元素设置:display: table-cell;

利用vertical和text-align可以让所有的行内块级元素水平垂直居中

子元素设置:display: inline-block;

<style>
    .father {
        width: 400px;
        height: 400px;
        background-color: black;

        display: table-cell;//设置table-cell
        vertical-align: middle;//子属性垂直居中
        text-align: center;//子属性水平居中
    }

    .son {
        width: 100px;
        height: 100px;
        background-color: white;
        display: inline-block;//设置为行内块
    }
</style>
<body>
<div class="father">
    <div class="son">
        水平垂直居中
    </div>
</div>
</body>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值