1、文字、行内元素在盒子中水平居中
p{ text-align: center; }
css基础知识
2、固定宽度的块级元素在父级盒子中水平居中
margin: 0 auto;
前提是宽度小于父级元素的宽度
.cen{ background: red; width: 300px; margin: 0 auto; /*float: left;*/ }
3、单行文字以及img、input等行内元素 垂直居中
line-height和height设置相同值
p{ border: 1px solid red; height: 200px; line-height: 200px; }
单行文字以及img、input等行内元素 垂直居中
css基础知识
4、绝对居中(水平居中,垂直居中)
方法一:
.box{ background: #da70d6; width: 300px; height: 300px; position: absolute; top:50%; left: 50%; margin-left: -150px; margin-top: -150px; }
方法二:
大家肯定会想margin:auto会不会实现水平垂直居中,答案是肯定的,只需要设置以下样式就可以啦~
.box1{ width: 500px; height: 500px; background: red; margin: auto; position: absolute; left: 0; top:0; right: 0; bottom:0; }
方法三:
通过css3的属性实现居中
.box2{ width: 50%; height: 50%; -webkit-transform: translate(-50%,-50%); -moz-transform: translate(-50%,-50%); -ms-transform: translate(-50%,-50%); -o-transform: translate(-50%,-50%); transform: translate(-50%,-50%); background: black; position: absolute; top:50%; left: 50%; }