1.行内元素水平居中显示
-
通过line-hinght + text-align
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> p{ width: 200px; height: 200px; background-color: #666; color:red; line-height: 200px; text-align:center; } </style> </head> <body> <p> 帅气的阿凯哥 </p> </body> </html>
-
通过给父元素设置display:table-cell,并且设置vertical-align:middle
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> span{ width: 200px; height: 200px; background-color: #666; color:red; text-align:center; display: table-cell; vertical-align:middle; } </style> </head> <body> <span> <span>你好啊</span> </span> </body> </html>
2.块级元素水平垂直居中
-
第一种:position+margin
- position,子绝父相,margin自动设置外边距
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .father{ width: 200px; height: 200px; background-color: red; position: relative; } .child{ position: absolute; width: 100px; height: 100px; background-color: blue; margin:auto; top:0; left:0; bottom:0; right:0; } </style> </head> <body> <div class="father"> <div class="child">居中盒子</div> </div> </body> </html>
-
第二种:display:table-cell
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .father{ width: 200px; height: 200px; background-color: red; display:table-cell; vertical-align:middle; text-align:center; } .child{ width: 100px; height: 100px; background-color: green; display:inline-block; vertical-align:middle; } </style> </head> <body> <div class="father"> <div class="child">居中盒子</div> </div> </body> </html>
- 第三种:position
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
.father{
width: 200px;
height: 200px;
background-color: red;
position: relative;
}
.child{
width: 100px;
height: 100px;
background-color: green;
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
}
</style>
</head>
<body>
<div class="father">
<div class="child">我是个居中的盒子</div>
</div>
</body>
</html>