<div id="box">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
</div>
#box{
display: flex;
display: -webkit-flex;
border: 1px solid #0000FF;
height: 200px;
width: 400px;
align-items:center;
justify-content:center;
}
.item{
width: 50px;
height: 40px;
border: 1px solid #00C1B3;
}
#box{
border: 1px solid #0000FF;
height: 200px;
width: 400px;
display:table-cell;
text-align: center;
vertical-align: middle;
}
.item{
width: 50px;
height: 40px;
border: 1px solid #00C1B3;
display: inline-block;
}
flex实现两端对齐
<h3>
<span>投资金额</span>
<span>美通卡奖励</span>
</h3>
h3{
width:100%;
height: 0.8rem;
/* line-height: 0.85rem; */
display: flex;
align-items: center;
justify-content: space-between;
}
一、定位+负边距
html部分
<body>
<div class="box"></div>
</body>
css部分
.box{
position:absolute;
left:50%;
top:50%;
margin-left:-150px;
margin-top:-100px;
padding:20px;
width:300px;
height:200px;
background:#41D7FB;
}
特点
- 兼容性较好,能够兼容到IE6
- 元素的宽高需要固定
- 比较经典的垂直居中实现方式
二、定位+自适应边距
html部分
<body>
<div class="box"></div>
</body>
css部分
.box{
position:absolute;
left:0;
right:0;
top:0;
bottom:0;
margin:auto;
padding:20px;
width:300px;
height:200px;
background:#41D7FB;
}
特点
- 兼容IE8以及以上浏览器
- 元素宽高不需固定,可以随内容适应
三、定位+CSS3位移
html部分
<body>
<div class="box"></div>
</body>
css部分
.box{
position:absolute;
left:50%;
top:50%;
transform: translate(-50%, -50%);
padding:20px;
width:300px;
height:200px;
background:#41D7FB;
}
特点
- 由于使用了CSS3中的transform属性,需要IE9+浏览器
- 元素宽高不需固定,可以随内容适应
四、Flex布局实现
html部分
<body>
<div class="box"></div>
</body>
css部分
html{
display: flex;
height: 100%;
justify-content: center;
align-items:center;
}
.box{
padding:20px;
width:300px;
height:200px;
background:#41D7FB;
}
特点
- 简单直接
- 兼容性较差,需要IE10+
- 父元素高度需要指定
- 元素的宽高可以随内容适应
五、table-cell配合inline-block
html部分
<body>
<div class="table">
<div class="table-row">
<div class="table-cell">
<div class="box"></div>
</div>
</div>
</div>
</body>
css部分
.table{
display:table;
width:100%;
height:600px;
}
.table-row{
display: table-row;
}
.table-cell{
display: table-cell;
text-align: center;
vertical-align: middle;
}
.box{
display: inline-block;
padding:20px;
width:300px;
height:200px;
background:#41D7FB;
}
特点
- 需IE8+兼容
- 元素宽高可以随内容适应
- 需设置较多的标签和css样式