ITPub博客

首页 > IT职业 > IT职场 > 水平垂直居中的实现方法

水平垂直居中的实现方法

IT职场 作者:yifanwu 时间:2021-09-09 09:51:19 0 删除 编辑

小div在大div里面水平垂直居中的实现方法

    初学前端时,我们都经常会练习实现关于水平垂直居中。那么你们都会用哪种方法呢?其实关于如何设置小盒子在大盒子里面水平垂直方向同时居中的实现方法有很多种,那么今天我就总结一下常用水平垂直居中的方法。

图片描述

(水平垂直居中效果图)


Ⅰ 方法一:使用定位的方法(如下图)

图片描述

(图1使用定位方法,需要知道子元素的宽高,但是不需要知道父元素的宽高.)

(我把我的样式代码粘贴到下边了)

.bg-box {width: 200px;height: 200px;margin:30px auto;border: 1px solid red;position:relative;}

.sm-box {width: 100px;height: 100px;border: 1px solid red;background: red;position:absolute; top: 50%;left:50%;margin-top: -50px; margin-left: -50px; } 


Ⅱ 方法二:利用定位及margin:auto实现(如下图)

图片描述

(图2实现原理是设置margin自动适应,然后设置定位的上下左右都为0,就如四边均衡受力从而实现盒子的居中;)

(我把我的样式代码粘贴到下边了)

.bg-box {width: 200px;height: 200px;margin:30px auto;border: 1px solid red;position:relative;}

.sm-box {width: 100px;height: 100px;border: 1px solid red;background: red;position: absolute;margin: auto;top: 0;left: 0;right: 0;bottom: 0;} 


Ⅲ 使用display:table-cell; (如下图)

图片描述

(图3实现原理: display:table-cell属性指让标签元素以表格单元格的形式呈现,类似于td标签.组合使用vertical-align,text-align,可以使父元素内的所有行内元素水平垂直居中(也就是将内部的元素设置display:inline-block))

(我把我的样式代码粘贴到下边了)

.bg-box {width: 200px; height: 200px;border: 1px solid red;display: table-cell;vertical-align: middle;text-align: center;}

 .sm-box { width: 100px;height: 100px;border: 1px solid red;background: red; display: inline-block; }       


Ⅳ 方法四:使用伸缩布局display:flex;(如下图)

图片描述

(图4 我觉得这个方法是最简单,最好用)

(我把我的样式代码粘贴到下边了)

.bg-box { width: 200px;height: 200px;border: 1px solid red;display: flex; justify-content: center;  align-items: center;        }

 .sm-box {width: 100px;height: 100px;border: 1px solid red; background: red;}     


Ⅴ 计算四周的间距设置子元素与父元素之间的margin-top和margin-left;(如下图)

图片描述

(图5方法需要同时知道父元素与子元素的宽高,不方便日后的维护.)

(我把我的样式代码粘贴到下边了)

.bg-box { width: 200px;height: 200px;border: 1px solid red; }

.sm-box { width: 100px;height: 100px;border: 1px solid red;  background: red;  margin-top: 50px; margin-left: 50px; }   

(总结这几种常见的方法,希望对初学前端者有用!    ---懿左左)



作者:懿左左
链接:https://www.jianshu.com/p/ec82fbc0c6be


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2157/viewspace-2813455/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-07-24

  • 博文量
    84
  • 访问量
    12526