考虑点:水平还是垂直;块还是行内;是否需要知道宽高;兼容性
水平居中:
块元素:margin: 0 auto
行内元素,行内块元素:text-align:center
垂直居中:
行内元素:line-height:xxpx
行内块元素:line-height:xxpx;vertical-align:middle
========================如果只使用line-height的效果======================
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
#p {
width: 400px;
height: 400px;
background-color: #f00;
line-height: 400px;
}
#c {
display: inline-block;
width: 200px;
height: 200px;
background-color: #000;
}
</style>
</head>
<body>
<div id="p">
<div id="c">
</div>
</div>
</body>
</html>
========================加上vertical-align:middle的效果======================
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
#p {
width: 400px;
height: 400px;
background-color: #f00;
line-height: 400px;
}
#c {
display: inline-block;
width: 200px;
height: 200px;
background-color: #000;
/* 以中线为基准进行居中 */
vertical-align: middle;
}
</style>
</head>
<body>
<div id="p">
<div id="c">
</div>
</div>
</body>
</html>
水平垂直同时居中:
absolute方法:
已知宽高:负数margin
===================举例========================
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
#p {
width: 400px;
height: 400px;
background-color: #f00;
position: relative;
}
#c {
width: 200px;
height: 200px;
background-color: #000;
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -100px;
}
</style>
</head>
<body>
<div id="p">
<div id="c">
</div>
</div>
</body>
</html>
已知宽高:calc(CSS3,IE8及以下不支持)
========================举例============================
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
#p {
width: 400px;
height: 400px;
background-color: #f00;
position: relative;
}
#c {
width: 200px;
height: 200px;
background-color: #000;
position: absolute;
/* top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -100px; */
top: calc(50% - 100px);
left: calc(50% - 100px);
}
</style>
</head>
<body>
<div id="p">
<div id="c">
</div>
</div>
</body>
</html>
需要设定宽高:margin auto
不需要设定宽高:transform(CSS3,IE8及以下不支持)