方案一:
div决定定位垂直水平居中(margin:auto实现绝对定位元素的居中)
兼容性:IE7以及之前版本不支持
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>垂直水平居中</title>
<style type="text/css">
#content {
width: 200px;
height: 200px;
background: lightblue;
position: absolute;
left: 0;
top: 0;
bottom: 0;
right:0;
margin: auto;
}
</style>
</head>
<body>
<div id="content"></div>
</body>
</html>
方案二:
div绝对定位垂直水平居中(margin负间距)这或许是当前最流行的使用方法。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>垂直水平居中</title>
<style type="text/css">
#content {
width: 200px;
height: 200px;
background: lightblue;
position: absolute;
left:50%;
top: 50%;
margin-left: -100px;
margin-top: -100px;
}
</style>
</head>
<body>
<div id="content"></div>
</body>
</html>
方案三:
div绝对定位垂直水平居中(Transforms变形)
兼容性:IE8不支持;
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>垂直水平居中</title>
<style type="text/css">
#content {
width: 200px;
height: 200px;
background: lightblue;
position: absolute;
left:50%;
top: 50%;
transform: translate(-50%,-50%);
}
</style>
</head>
<body>
<div id="content"></div>
</body>
</html>
方案四:
使用flex
css高垂直水平居中(相对于父级元素)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>垂直水平居中</title>
<style type="text/css">
.box {
height: 600px;
border: 2px solid black;
display: flex;
justify-content: center;
align-items: center;
}
#content {
background: lightblue;
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<div class="box">
<div id="content"></div>
</div>
</body>
</html>
方案五:
使用flex
使div在整个页面垂直水平居中
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>垂直水平居中</title>
<style type="text/css">
html,body {
height: 100%;
}
body {
display: flex;
align-items: center;
justify-content: center;
}
#content {
background: lightblue;
margin: 0 auto;
}
</style>
</head>
<body>
<div id="content">垂直水平居中</div>
</body>
</html>
方案六:
使用display:table-cell
css高垂直水平居中(相对于父级元素)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>垂直水平居中</title>
<style type="text/css">
.box {
width: 300px;
height: 300px;
border: 2px solid black;
display: table-cell;
text-align: center;
vertical-align: middle;
}
#content {
width: 100px;
height: 100px;
background: lightblue;
display: inline-block;
}
</style>
</head>
<body>
<div class="box">
<div id="content">垂直水平居中</div>
</div>
</body>
</html>
总结:css的布局还是需要多多练习,今天做笔试时突然发现自己在这一块有些遗忘了,所以整理了这六种跟可以让div垂直居中的方法,分别是绝对布局和flex,table-cell演变出来的,如果还有其他更好的方法还望大家多多交流~