CSS居中设置

方法一:
  1. 父级元素position: relative
  2. 子元素position: absolute;top:50%;left: 50%;margin-left: -(子元素width/2);margin-top: -(子元素height/2);

 1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="utf-8">
5 <title></title>
6 <style type="text/css">
7 {
8 margin: 0;
9 padding: 0
10 }
11 /方法一:/
12 .parent{
13 margin: 100px;
14 width: 300px;
15 height: 200px;
16 border: 1px solid red;
17 position: relative;
18 }
19 .child{
20 width: 150px;
21 height: 100px;
22 background-color: red;
23 position: absolute;
24 top:50%;
25 left: 50%;
26 margin-left: -75px;
27 margin-top: -50px;
28 }
29 </style>
30 </head>
31 <body>
32 <div class="parent">
33 <div class="child"></div>
34 </div>
35 </body>
36 </html>

方法二

 1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="utf-8">
5 <title></title>
6 <style type="text/css">
7 {
8 margin: 0;
9 padding: 0
10 }
11 /方法二,这种方法只能在IE8+、谷歌、火狐等浏览器上使用,IE6、IE7都无效。/
12 .parent{
13 display:table-cell;
14 vertical-align: middle; /垂直居中/
15 text-align: center; /水平居中:子元素必须是inline-block/
16 width: 300px;
17 height: 200px;
18 border: 1px solid red;
19 }
20 .child{
21 display: inline-block; /设置此属性才能水平居中/
22 width: 150px;
23 height: 100px;
24 background-color: red;
25 }
26 </style>
27 </head>
28 <body>
29 <div class="parent">
30 <div class="child"></div>
31 </div>
32 </body>
33 </html>

方法三

 1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="utf-8">
5 <title></title>
6 <style type="text/css">
7 {
8 margin: 0;
9 padding: 0
10 }
11 /方法三:*/
12 .parent{
13 width: 300px;
14 height: 200px;
15 border: 1px solid red;
16 position: relative;
17 }
18 .child{
19 width: 150px;
20 height: 100px;
21 background-color: red;
22 position: absolute;
23 top: 0;
24 left: 0;
25 right: 0;
26 bottom: 0;
27 margin: auto;
28 }
29 </style>
30 </head>
31 <body>
32 <div class="parent">
33 <div class="child"></div>
34 </div>
35 </body>
36 </html>

页面显示如下图

返回
顶部