css水平垂直居中方法

xiaoxiao2021-02-28  37

HTML代码

<head> <meta charset="UTF-8"> <link rel="stylesheet" href="index.css"> </head> <body> <div class="container"> <div class="box" >Lorem ipsum dolor sit, amet consectetur </div> </div> </body> </html>

1.文本水平居中

如果是行内块元素实现居中也可以使用,不过要定义在 父元素上

.box{ text-align: center; }

2.单行文本垂直居中

div{ display: inline-block; height: 40px; line-height: 40px; background: blue ; }

3.flexbox实现水平垂直居中

flex是在父元素上定义的,使用flex的时候要考虑浏览的兼容性

.container{ display: flex; justify-content: center; align-items: center; height: 250px; background: red; }

4.margin设为auto实现水平居中

元素必须为块元素,而且有确定的宽度

.box{ display: block; width: 310px; margin: 0 auto; }

5.浮动元素实现水平居中

.container{ width: fit-content; margin: 0 auto; } .box{ float: left; }

6.position绝对定位和transform来实现水平垂直居中

绝对定位元素的定位基准点是其有定位元素的祖先元素,而translate要做偏移,是相对于自身的中心点而言,用百分比做单位,参考值是本身元素的宽度。下面有图片解释:

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

原理:

7. position绝对定位(top,bottom,left,right)和margin实现水平垂直居中

条件:元素必须有固定的宽高才能实现,img可以不用设置宽高,自带

.box{ position: absolute; width: 310px; height: 21px; margin: auto; top: 0; bottom: 0; left: 0; right: 0; }
转载请注明原文地址: https://www.6miu.com/read-2620117.html

最新回复(0)