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

目录

1.flex布局

2.定位+margin

3.定位+translate

4.网格布局(grid)

5.table布局

6.::before伪元素布局

 

要实现的两个嵌套盒子,parent为父盒子外面的大盒子,child为里面的小盒子。全文html结构都为此。

<div id="parent">

        <div id="child"></div>

    </div>

css文件宽高背景颜色随便设置,只是为了方便看效果。

1.flex布局

#parent{width:200px;height:200px;background:pink;

    /* 第一种方式:使用flex布局 

    给父元素设置flex布局使子元素在内部垂直居中,flex中有两个属性align-items,justify-conten分别代表水平垂直的位置,均设置为center即可实现子元素居中*/

    display:flex;

    align-items: center;

    justify-content: center; 

}

#child{background:rgb(14, 113, 179);width:50px;height:50px;

    /* 直接给子元素设置margin也可以,只给父元素一个display ,flex属性和margin不一同使用,但是都可以实现居中效果,下面讲的grid同理*/

    margin:auto;

}


2.定位+margin

#parent2{width:200px;height:200px;background:rgb(192, 255, 213);

    /* 第二种方式:使用绝对定位,父元素设置相对定位relative,子元素相对于父元素进行绝对定位

    接着设置子元素左上角居中,即距离父元素上边和左边各一半,在减去外边距自己宽高的一半实现子元素中心点居中*/

    position:relative;

}

#child2{background:red;width:50px;height:50px;

    position: absolute;

    top:50%;

    left:50%;

    margin-left:-25px;

    margin-top:-25px;

}

3.定位+translate

#parent3{width:200px;height:200px;background:rgb(99, 25, 148);

    /* 第三种方式:使用绝对定位,

    使用tranlata进行平移,与第二种方法类似,原理相同*/

    position:relative;

}

#child3{background:red;width:50px;height:50px;

    position: absolute;

    top:50%;

    left:50%;

    transform: translate(-50%,-50%);

}


4.网格布局(grid)

#parent4{width:200px;height:200px;background:rgb(207, 130, 13);

    /* 第四种方式:使用网格布局grid

    给父元素display设置网格布局,子元素设置垂直居中

    直接设置margin也可以,与flex类似*/

    display:grid;

}

#child4{background:red;width:50px;height:50px;

可以直接设置属性,,也可以不设置属性直接写margin

    justify-self: center;

    align-self: center;

    /* margin:auto; */

}


5.table布局

#parent5{width:200px;height:200px;background:rgb(205, 142, 224);

    /* 第五种方式:使用table布局

    给父元素设置table-cell,水平垂直居中,给子元素设置为行内元素*/

    display:table-cell;

    vertical-align: middle;

    text-align: center;

}

#child5{background:rgb(51, 228, 16);width:50px;height:50px;

    display: inline-block;

}

6.::before伪元素布局

#parent6{width:200px;height:200px;background:rgb(69, 74, 75);

    /* 第六种方式:使用伪元素before

    内容设置空,设为行内元素,宽为0,高100%,垂直居中

    子元素同样设置为行内元素,垂直居中*/

    font-size: 0;

    text-align: center;

}

#parent6::before{

    content: "";

    display: inline-block;

    width: 0;

    height: 100%;

    vertical-align: middle;

}

#child6{background:rgb(236, 241, 235);width:50px;height:50px;

    display: inline-block;

    vertical-align: middle;

}

猜你喜欢

转载自blog.csdn.net/luobo2345/article/details/112863294