div垂直居中的几种方法

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

图片.png

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

.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实现(如下图)

图片.png

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

.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; (如下图)

图片.png

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

.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;(如下图)

图片.png

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

.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;(如下图)

图片.png

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

.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; }

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容