css垂直居中

在CSS中水平居中是非常简单的:
如果是一个行内元素,就再它的父元素添加text-align: center,如果是一个块级元素自身添加margin: auto属性。
垂直居中是比较麻烦的,今天介绍几种垂直居中的方法。

1.单行文本垂直(line-height)

代码

效果:

这里写图片描述

2.块级(包含行内块)元素垂直居中

早期的做法,它要求元素定宽定高

<style>
    .box2 {
            width: 400px;
            height: 200px;
            border: 1px solid #ff0000;
            position: relative
        }
        .box2>div {
            position: absolute;
            top: 50%;
            left: 50%;
            margin-top: -50px; /* -(height/2) */
            margin-left: -50px; /* -(width/2) */
            width: 100px;
            height: 100px;
            background: yellow;
        }
</style>

<!--html代码-->
<div class="box2">
    <div></div>
</div>

这个方法的本质是:看下图

这里写图片描述

3.position + transform实现垂直居中(不定高,不定宽)
<style>
        .box3 {
            width: 400px;
            height: 200px;
            border: 1px solid #ff0000;
            position: relative
        }
        .box2>div {
            position: absolute;
            top: 50%;
            left: 50%;
            width: 100px;
            height: 100px;
            transform: translate(-50%, -50%);
            background: yellow;
        }
</style>

<!--html代码-->
<div class="box3">
    <div></div>
</div>

4.使用table-cell(适合于文字)

    <style>
        .box {
            display: table-cell;
            vertical-align: middle;
            text-align: center;
            width: 300px;
            height: 300px;
            background: purple;
        }
        .box span {
            display: inline-block;
            vertical-align: middle;
        }
    </style>
    <div class="box">
        <span>多行文字,此处居中设置</span>
    </div>

此时span在容器box中处于居中

5.使用flex布局(不定高,不定宽)

     <style>
          .flex {
              display: flex;
              /* 垂直居中 */
              align-items: center;
              width: 300px;
              height: 300px;
              /* 水平居中 */
              justify-content: center;
              background: #ff0000;
          }
     </style>
     <div class="flex">
         <div class="flex-item">123</div>
     </div>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值