css怎么设置多行垂直居中
1、新建一个html页面,首先,将页面(多行元素)的基本结构写出来:
例子:
<div id="container">
<span>多行水平垂直居中</span>
<span>多行水平垂直居中</span>
<span>多行水平垂直居中</span>
<span>多行水平垂直居中</span>
<span>多行水平垂直居中</span>
</div>
2、给容器#container添加css样式,要让行内元素垂直居中,必须已知容器的宽高;对于行内元素我们可以用display:table,无需知道行内元素的宽高
css:
#container{
margin:20px auto;
background: #ccc;
position: relative;
width:900px;
height:600px;
display: table;
}
3、给行内元素添加样式:display:table-row 让行内元素垂直居中;
然后再添加水平居中样式:text-align: center;
如果需要让行内元素的文字也垂直居中的话,就根据容器的高度(600px)分成五等分,即120px;添加样式:line-height:120px;
CSS:
#container span{
display: table-row;
text-align: center;
line-height: 120px;
}
1、首先,将页面的多个块状元素的基本结构写出来,如下:
<div class="test3">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
2、使用弹性盒子
弹性盒子将父级元素设置为(注意兼容性):
display:-webkit-box;
display:-moz-box;
display:-ms-box;
display:box;
控制子元素的方向,让子元素竖排:
-webkit-box-orient:vertical;
-moz-box-orient:vertical;
-ms-box-orient:vertical;
box-orient:vertical;
CSS:
.test3{
width:800px;
margin:30px auto;
height:600px;
border: 10px solid #ccc;
padding: 10px;
display:-webkit-box;
display:-moz-box;
display:-ms-box;
display:box;
-webkit-box-orient:vertical;
-moz-box-orient:vertical;
-ms-box-orient:vertical;
box-orient:vertical;
}
给子元素设置宽高:
.test3 div{
width:100px;
height:100px;
background: red;
border: 1px solid #fff;
}
效果如图:
3、根据父级元素的高度、子元素的高度及每一子元素有1px的边框,600-100*5-2*5=90;然后将90分成六等分,即:15px,给子元素添加样式: margin: 15px auto 0 auto;
子元素CSS样式:
.test3 div{
width:100px;
height:100px;
background: red;
border: 1px solid #fff;
margin: 15px auto 0 auto;
}
效果如图: