div水平居中,垂直居中的几种方式

假设我们现在要实现box元素的居中
123
/* 公共代码 */ .wp { border: 1px solid red; width: 300px; height: 300px; } .box { background: green; } .box.size{ width: 100px; height: 100px; } /* 公共代码 */ 1.box确定宽高
fff
1.1absolute + 负margin /* 定位代码 */ .wp { position: relative; } .box { position: absolute;; top: 50%; left: 50%; margin-left: -50px; margin-top: -50px; } 1.2absolute + margin auto .wp { position: relative; } .box { position: absolute;; top: 0; left: 0; right: 0; bottom: 0; margin: auto; } 1.3absolute + calc .wp { position: relative; } .box { position: absolute;; top: calc(50% - 50px); left: calc(50% - 50px); } 2.box不确定宽高
123
2.1absolute + transform .wp { position: relative; } .box { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } 2.2.flex布局 .wp { display: flex; justify-content: center; align-items: center; } 2.3table-cell .wp { display: table-cell; text-align: center; vertical-align: middle; } 2.4lineheight .wp { line-height: 300px; text-align: center; font-size: 0px; } .box { font-size: 16px; display: inline-block; vertical-align: middle; line-height: initial; text-align: left; }

本文章由javascript技术分享原创和收集

发表评论 (审核通过后显示评论):

昵称:
邮箱:
内容: