居中方法
1.margin:auto居中法
- 父元素相对定位
- 子元素绝对定位
top,bottom,left,right均设0.
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<style type="text/css">
.father{
width: 200px;
height: 200px;
background: red;
position: relative;
}
.childer{
background: blue;
width: 50px;
height: 50px;
margin: auto;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
</style>
<body>
<div class="father">
<div class="childer">
123
</div>
</div>
</body>
</html>
2.负值居中法
-
父元素相对定位
-
子元素宽高固定
-
子元素绝对定位,left: 50%;top:50%
-
子元素设置margin-left,margin-top.数值为子元素宽高的一半.
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <style type="text/css"> .father{ width: 200px; height: 200px; background: red; position: relative; } .childer{ background: blue; width: 50px; height: 50px; margin: auto; position: absolute; left:50%; top: 50%; margin-left: -25px; margin-top: -25px; } </style> <body> <div class="father"> <div class="childer"> 123 </div> </div> </body> </html>
3.table-cell居中法
-
父元素设为table-cell
-
子元素设为inline-block,或margin:auto
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <style type="text/css"> .father{ width: 200px; height: 200px; background: red; display: table-cell; vertical-align: middle; text-align: center; } .childer{ background: blue; width: 50px; height: 50px; display: inline-block;//或者不同display而是使用 margin:auto /* margin: auto; */ } </style> <body> <div class="father"> <div class="childer"> 123 </div> </div> </body> </html>
4.flex居中法
-
父元素设为flex,并进行配套设置
-
子元素无要求
-
该方法极度好用,但是兼容性不好(ie10)
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <style type="text/css"> .father{ width: 200px; height: 200px; background: red; display: flex; justify-content: center; align-items: center; } .childer{ background: blue; width: 50px; height: 50px; } </style> <body> <div class="father"> <div class="childer"> 123 </div> </div> </body> </html>
5.vertical-align:middle居中法
-
父元素设置text-align,line-height.
-
子元素设置为inline-block,vertical-align
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <style type="text/css"> .father{ width: 200px; height: 200px; background: red; text-align: center; line-height: 200px; } .childer{ background: blue; width: 50px; height: 50px; display: inline-block; vertical-align: middle; } </style> <body> <div class="father"> <div class="childer"> 123 </div> </div> </body> </html>
总结
- 前两种方法为常用方法.
- 尽量少用display:inline-block. 因为不咋符合w3c规定.