div水平垂直居中方法(前端面试必备)

div水平垂直居中方法

方法1.这也是绝大多数网友使用的方法
这里写图片描述

<div class="fa">
    <div class="left1">

    </div>
</div>
//-----------样式-----------------
        .fa{
            position:relative;
            width: 100%;
            height: 2rem;
            background-color:red;
        }
        .left1{
            position:absolute;
            width: 1.5rem;
            height: 1.5rem;
            top:50%;
            left:50%;
            margin-left:-0.75rem;
            margin-top:-0.75rem;
            background-color: #000000;
        }
(这种方法能够实现水平垂直居中,但样式代码太多了)

方法1的升级写法,使用calc();(个人比较推荐的写法!)
.left1{
position:absolute;
width: 1.5rem;
height: 1.5rem;
top:calc(50% - 0.75rem);
left:calc(50% - 0.75rem);
background-color: #000000;
}
注意:1.calc()的表达式中运算符两边必须要有空格。
说明:left:calc(50% - 0.75rem)中的0.75rem是指需要水平垂直居中的div的宽或高的一半;50%是指父级容器的50%,及一半,这里的父级容器的宽度为100%;
同理:top:calc(50% - 0.75rem)就不在说明。
方法2.
这里写图片描述

    <div class="fa2">
        <div class="left2">

        </div>
    </div>
    //-----------样式-----------------
        .fa2{
            width: 100%;
            height: 2rem;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: yellow;
        }
        .left2{
            width: 1.5rem;
            height: 1.5rem;
            background-color: green;
        }

第二种方法是直接在父盒子中写样式

猜你喜欢

转载自blog.csdn.net/li11_/article/details/53742937