这个在实际中很常见,用jquery是很容易实现,用table也很容易实现。其余的方式兼容性其实来都非常差,代码也不易读。
好在有css3,基本上大部分浏览器也支持了。
html和body默认的高度为1行,所以还需要增加,
html,body{
height:100%;
margin:0;
}
justify-content:center;//子元素水平居中
align-items:center;//子元素垂直居中
display:-webkit-flex;
利用css3的flex属性
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
html,body{
height:100%;
margin:0;
}
#box{
display:flex;
height:100%;
width: 100%;
/*justify-content属性定义了子项目在主轴上(X轴)的对齐方式。*/
justify-content: center;
/*align-items属性定义子项目在交叉轴(Y轴上)上如何对齐。*/
align-items: center;
}
.item{
width: 50px;
height: 40px;
border: 1px solid #00C1B3;
}
</style>
</head>
<body>
<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>
</body>
</html>
也可以利用css的 transform,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS垂直居中</title>
<style>
.wrapper{
width: 500px;
height: 500px;
background-color: pink;
text-align: center;
}
.box{
width:100px;
height:100px;
background-color:#f50;
position: relative;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
</style>
</head>
<body>
<div class="wrapper">
<div class="box"></div>
</div>
</body>
</html>