1、水平居中
將margin-left和margin-right屬性設置為auto,從而達到水平居中的效果。
代碼:
margin:0 auto;
2、文字水平垂直居中
利用line-height設為height的一樣
代碼:
line-height: 200px;/*垂直居中關鍵*/
height: 200px;
3、利用padding和background-clip配合實現div的水平垂直居中
通過backgroun-clip設置為content-box,將背景裁剪到內容區外沿,再利用padding設為外div減去內div的差的一半
1 .parent{
2 margin:0 auto;
3 width:200px;
4 height:200px;
5 background-color:red;
6 }
7 .children {
8 width: 100px;
9 height: 100px;
10 padding: 50px;
11 background-color: black;
12 background-clip:content-box;/*居中的關鍵*/
4、absolute定位
其中的margin中的值為該div寬度的一半
利用position:absolute搭配top,left 50%,再將margin設為負值也可以對div進行水平垂直居中
1 .parent {
2 position:relative;
3 margin:0 auto;
4 width:200px;
5 height:200px;
6 background-color:red;
7 }
8 .children {
9 position:absolute;
10 left:50%;
11 top:50%;
12 margin:-25px 0 0 -25px ;
13 height:50px;
14 width:50px;
15 background-color: black;
16 }
5、text-align居中
將子div的display設為inline-block。
1 .parent {
2 text-align:center;
3 margin:0 auto;
4 width:200px;
5 height:200px;
6 background:red;
7 }
8 .children {
9 positiona;absolute; 10 margin-top:75px;
11 width:50px;
12 height:50px;
13 background: black;
14 display:inline-block;/*使其父元素text-align生效*/
15 }
圖片居中
1、top
1 position:absolute; 2 right:50%; 3 bottom:50%;
2、transform
不需要定寬度的父div實現圖片的水平垂直居中
1 <div class="parent">
2
3 <div class="children">
4
5 <div class="children-inline">我是水平垂直居中噢!</div>
6
7 </div>
8
9 </div>
1 .parent {
2 float: left;
3 width: 100%;
4 height: 200px;
5 background-color: red;
6 }
7 .children {
8 float:left;
9 position:relative;
10 top:50%;
11 left:50%;
12 }
13 .children-inline {
14 position: relative;
15 left: -50%;
16 -webkit-transform : translate3d(0, -50%, 0);
17 transform : translate3d(0, -50%, 0);
18 background-color: black;
19 color:white;
20 }
3、flex水平垂直居中
1 <div class="parent">
2
3 <div class="children">我是通過flex的水平垂直居中噢!</div>
4
5 </div>
1 html,body{
2 width: 100%;
3 height: 200px;
4 }
5 .parent {
6 display:flex;
7 align-items: center;/*垂直居中*/ 8 justify-content: center;/*水平居中*/
9 width:100%;
10 height:100%;
11 background-color:red;
12 }
13 .children {
14 background-color:blue;
15 }
1 水平居中 2 .center-vertical {
3 position: relative;
4 top: 50%;
5 transform: translateY(-50%);
6 }
7
8
9
10 垂直居中 11 .center-horizontal {
12 position: relative;
13 left: 50%;
14 transform: translateX(-50%);
15 }