居中的问题我一般用的是两种方法。
1.line-height:
将要居中的元素的height和line-height设置成相同高度,这样它就居中了。
//这个是用做单行居中的,注意,是单行居中,如果想要多行居中或者多个元素居中,这个就不能用。
2.多行居中
将你要居中的元素的父元素设置为relative,它们的position设置为absolute,然后将top,bottom设置为0,margin设为auto,如果要达到它们是靠右或者靠左的,就设置left或者right为0,不要用float,position不要一起用。
下面是一个多行居中的代码。
<!DOCUTYPE html>
<html>
<head>
<style>
.d1{
width:300px;
height:300px;
background:red;
position:relative;
}
.d2,.d3{
width:100px;
height:100px;
line-height:100px;
}
.d2{
background:blue;
}
.d3{
background:yellow;
}
.s1{
position:absolute;
top:0;
bottom:0;
right:0;
margin:auto;
height:200px;
}
</style>
</head>
<body>
<div class="d1">
<span class="s1">
<div class="d2">d2</div>
<div class="d3">d3</div>
</span>
</div>
</body>
</html>
效果如图: