我是小渔歌,点击右上方“关注”,每天为你分享【前端技术知识】干货。

首先,定义一个父盒子parent,一个子盒子child。

/* 父子公共样式开始 */ .parent { width: 300px; height: 100px; border: 1px solid #000000; } .child { border: 1px solid #000000; display: inline-block; } /* 父子公共样式结束 */ <!-- 父子元素开始 --> <div class="parent"> <div class="child"> child </div> </div> <!-- 父子元素结束 -->

水平居中方式

css的居中怎么设置(CSS的居中方式居然有那么多)(1)

水平居中图示

1、table margin

.child { display: table; margin: 0 auto; }

2、absolute transform

.parent { position: relative; } .child { position: absolute; left: 50%; transform: translateX(-50%); }

3、inline-block text-align

.parent { text-align: center; } .child { display: inline-block; }

4、flex justify-content

.parent { display: flex; justify-content: center; }

5、flex margin

.parent { display: flex; } .child { margin: 0 auto; }

6、absolute margin

注意:必须已知子元素的宽度。

.parent { position: relative; } .child { position: absolute; top: 50%; margin-left: - 子元素宽度的一半px; }

垂直居中方式

css的居中怎么设置(CSS的居中方式居然有那么多)(2)

垂直居中图示

1、absolute transform

.parent { position: relative; } .child { position: absolute; top: 50%; transform: translateY(-50%); }

2、flex align-items

.parent { display: flex; align-items: center; }

3、table-cell vertical-align

.parent { display: table-cell; vertical-align: middle; }

4、absolute margin

注意:必须已知子元素高。

.parent { position: relative; } .child { position: absolute; top: 50%; margin-top: - 子元素高度的一半px; }

水平垂直居中方式

css的居中怎么设置(CSS的居中方式居然有那么多)(3)

水平居中图示

1、flex

.parent { display: flex; align-items: center; justify-content: center; }

2、父元素relative,子元素absolute,设置transform,left,top

.parent { position: relative; } .child { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); }

3、父元素relative,子元素absolute,设置transform,margin-left,margin-top

注意:必须已知子元素宽高。

.parent { position: relative; } .child { position: absolute; left: 50%; top: 50%; margin-top: - 子元素高度的一半px; margin-left: - 子元素宽度的一半px; }

4、父元素table-cell,vertical-align,text-align

.parent { display: table-cell; vertical-align: middle; text-align: center; } .child { display: inline-block; }

5、line-height

.parent { text-align: center; line-height: 100px; } .child { display: inline-block; line-height: 20px; }

6、display:-webkit-box属性,再设置-webkit-box-pack:center/-webkit-box-align:center

.parent { display: -webkit-box; -webkit-box-pack: center; -webkit-box-align: center; }

大家还知道什么居中方式,一起探讨下。

往期精彩内容

能用CSS实现的效果,就尽量把Javascript踢开吧?

在JavaScript中call与apply的实际应用你知道多少?

,