[css]盒子水平垂直居中的6种方法 您所在的位置:网站首页 弹性盒子上下对齐怎么调 [css]盒子水平垂直居中的6种方法

[css]盒子水平垂直居中的6种方法

2023-10-20 16:56| 来源: 网络整理| 查看: 265

让盒子水平垂直居中是前端很基础的知识,在前端的面试中也经常会考查到,今天我就整理总结一下盒子水平垂直居中的几种方法。

盒子的设定 父盒子:width: 400px; height: 500px;子盒子:width: 100px; height: 100px; (当然也可以是其他数值,只是为了统一得到一个结果就提前给个设定) 预期结果

在这里插入图片描述

方法 1.定位法

利用子绝父相,给父盒子添加相对定位子盒子添加绝对定位 代码如下:

定位完成盒子水平垂直居中 .box{ position: relative; width: 400px; height: 500px; background-color: skyblue; } .box1{ position: absolute; left: 50%; top: 50%; margin-left: -50px; margin-top: -50px; width: 100px; height: 100px; background-color: orange; } 2.margin:auto;

其实也是定位的方法,只是定位时使用了margin 代码如下:

margin完成盒子水平垂直居中 .box { position: relative; width: 400px; height: 500px; background-color: skyblue; } .box1 { position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; width: 100px; height: 100px; background-color: orange; } 3.利用 display:table-cell

把父盒子转化为单元格,子盒子转化为行内块元素,再给父盒子设置文字居中 代码如下:

table-cell完成盒子水平垂直居中 .box { display: table-cell; text-align: center; vertical-align: middle; width: 400px; height: 500px; background-color: skyblue; } .box1 { display: inline-block; width: 100px; height: 100px; background-color: orange; } 4.flex布局。display:flex;

比较轻松的方式,在实际应用中用的较多 代码如下;

flex完成盒子水平垂直居中 .box { display: flex; justify-content: center; align-items: center; width: 400px; height: 500px; background-color: skyblue; } .box1 { width: 100px; height: 100px; background-color: orange; } 5.计算父盒子和子盒子之间的距离

比较麻烦,不实用。而且用这个方法必须给盒子添加边框。 代码如下:

计算距离完成盒子水平垂直居中 .box { width: 400px; height: 500px; background-color: skyblue; border: 1px solid black; } .box1 { width: 100px; height: 100px; background-color: orange; border: 1px solid black; margin-top: 200px; margin-left: 150px; } 6.利用 transform

其实也是定位法,跟第一个方法原理一致 代码如下:

计算距离完成盒子水平垂直居中 .box{ position: relative; width: 400px; height: 500px; background-color: skyblue; } .box1{ position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); width: 100px; height: 100px; background-color: orange; }

其实说是6种方法其实按照原理来说只有5种,因为1和6都用了定位的方法. 目前我整理出来就这几种方法,大家有更好的方法也可以评论区分享出来。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有