当前位置:Gxlcms > css > css水平垂直居中的4种实现方法

css水平垂直居中的4种实现方法

时间:2021-07-01 10:21:17 帮助过:29人阅读

本文主要和大家分享css水平垂直居中的4种实现方法,方案中我也给了宽高,但并不是说宽高固定了。而是以为不给宽高无法看到效果。这个方案不固定宽高的是指,用这个方案之后,如果你父元素、子元素的宽高发生了改变,依旧可以保证是水平垂直居中的位置。

下面四种方案都是能够实现,当父元素或子元素的宽高发生改变时,依旧维持水平垂直居中布局的方案。

方案1: 定位

html

         <p class="father">
            <p class="son"></p>
         </p>

css

        .father {
            position: relative;
            width: 200px;
            height: 200px;
            background: skyblue;
        }
        .son {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%,-50%);
            width: 100px;
            height: 100px;
            background: red;
        }

方案2: flex

html不变

        <p class="father">
            <p class="son"></p>
        </p>

css

        .father {
            display: flex;
            justify-content: center;
            align-items: center;
            width: 200px;
            height: 200px;
            background: skyblue;
        }
        .son {
            width: 100px;
            height: 100px;
            background: red;
        }

方案3: table布局

需要设置父元素为display:table-cell,利用vertical和text-align可以让所有的行内块级元素水平垂直居中
给子元素设置 display: inline-block

html 不变

  <p class="father">
        <p class="son"></p>
    </p>

css

  .father {
            display: table-cell;
            width: 200px;
            height: 200px;
            background: skyblue;
            vertical-align: middle;
            text-align: center;
        }
        .son {
            display: inline-block;
            width: 100px;
            height: 100px;
            background: red;
        }

方案4: grid布局 (最新浏览器支持)

html不变

        <p class="father">
            <p class="son"></p>
        </p>

css不变

        .father {
            display: grid;
            align-items:center;
            justify-content: center;
            width: 200px;
            height: 200px;
            background: skyblue;

        }
        .son {
            width: 10px;
            height: 10px;
            border: 1px solid red
        }

相关推荐:

html的元素水平垂直居中应该怎么设置

css如何实现水平垂直居中以及两端对齐的代码分享

CSS实现水平垂直居中的几种方法介绍

以上就是css水平垂直居中的4种实现方法的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行