1

使用css居中有很多种方式,在这里写几个最佳实践。代码简单粗暴,适用性强,让你不必这点小事烦恼,提升你的工作效率,早几分钟下班回家LOL岂不是美滋滋
不多说废话,直接上代码

  • 基本的样式和布局
<div class="container">
        <div class="inner">
        </div>
 </div>
    .container {
        height: 200px;
        width: 200px;
        background: #369;
    }

    .inner {
        height: 50px;
        width: 50px;
        background: #963;
    }

image.png

  • 左右居中最简单的两种写法
    <p>左右居中1</p>
    <div class="container center1">
        <div class="inner center-inner1">

        </div>
    </div>

    <p>左右居中2</p>
    <div class="container center2">
        <div class="inner">
        </div>
    </div>
 .center1 {
        text-align: center;
    }

    .center-inner1 {
        display: inline-block;
    }

    .center2 {
        display: flex;
        justify-content: center;
    }

    .center-inner2 {
        display: inline-block;
    }

image.png

  • 垂直居中的两种最简单写法
<p>垂直居中1</p>
    <div class="container center3">
        <div class="inner center-inner3"></div>
    </div>

    <p>垂直居中2</p>
    <div class="container center4">
        <div class="inner center-inner4"></div>
    </div>
 .center3 {
        display: flex;
        align-items: center;
    }

    .center4 {
        position: relative;
    }

    .center-inner4 {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
    }

image.png

  • 左右居中+垂直居中
    <p>左右居中+垂直居中</p>
    <div class="container center5">
        <div class="inner"></div>
    </div>
    .center5 {
        display: flex;
        align-items: center;
        justify-content: center;
    }

image.png

点个收藏关注一下不迷路


波罗丁的菠萝
886 声望14 粉丝

深林人不知,明月来相照