有哪里不懂的,请在下面留言,我每天都看,有时间我会一一解答,看评论区也许有人提出了跟你同样想问的问题,可以看看我给出的回答,不用重复提问。
不说废话直接开始。
单行文本垂直居中
#kexuejiafivefiveopen { width: 200px; height: 100px; line-height: 100px; text-align: center; background: pink; color: gray;}复制代码单行文文本垂直居中
- 此方法只适用于单行且较短的文本,如果是多行文本或单行较长的文本则会溢出
- 单行短文本居中的重点在于文本的基线(自行百度),文本的行高和容器的高度达到一致,由于文本的基线问题则该文本垂直居中
- line-height是可以继承的,line-height细节十分讲究请自行查阅相关资料
多行文本块display:table垂直居中
#cixitaihou { width: 600px; height: 100px; background: pink; color: gray; overflow: hidden; display: table;}#uhuang { display: table-cell; vertical-align: middle; height: 50px; background: yellow;}复制代码多行文本table块垂直居中
- 此方法适用于多行文本块居中
- 此方法利用了display:table的特性给父盒子转换为table给盒子设置table-cell加上vertical-align:center,vertical-align属性十分讲究请自己查阅相关资料
absolute居中-上下左右0+margin:auto
#fuck { width: 400px; height: 100px; background: pink; position: relative;}#fuck .you { position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; height: 50px; width: 50%; background: yellow; color: gray;}复制代码absolute上下左右0配合margin:auto
- 此方法重点在于absolute在父盒子里的top,right,bottom,left的值均为零,同时要设置margin:auto
- 有个小细节是.you盒子的高度是百分比,说明百分比的盒子也适用于这种方法
absolute+transform居中
#fuck { width: 400px; height: 100px; background: #161616; color: #fff; position: relative;} #fuck .you { position: absolute; left: 50%; top: 50%; background: #999; transform: translateX(-50%) translateY(-50%);}复制代码absolute+transform居中
- left:50%,top:50%是基于.you的最左上角定点移动,transform: translateX(-50%) translateY(-50%);是把.you自身的50%进行移动,因为left:50%,top:50%移动过头了,所以要用 translateX和Y设置为负值反向退回来从而达到居中
absolute固定自减居中
#fuck { width: 400px; height: 100px; background: pink; color: gray; position: relative; }#fuck .you { height: 50px; width: 200px; position: absolute; left: 50%; top: 50%; margin-top: -25px; margin-left: -100px; background: yellow;}复制代码块区域垂直居中
- 这个方法只适合在你这个东西固定宽高的情况下使用,道理和上面translate一样,left和right移动了50%再用负值的margin拉回来
- 在使用margin的时候有可能会顶开或者遮盖住其他元素,看情况使用。
margin填充居中
#fuck { width: 400px; height: 100px; background: pink; color: gray; overflow: hidden;}#fuck .you { margin-left: auto; margin-right: auto; margin-top: calc((100px - 50px)/2); height: 50px; background: yellow;}复制代码margin:calc计算
- margin左右auto可以让块级元素水平居中,但是margin上下auto却不能使其垂直居中,这个方法的前提是确定了父子盒子的高度用css3的计算calc计算出一个数值给margintop把自己顶下来,慎用。