CSS水平垂直居中
阿新 • • 發佈:2017-05-16
水平居中 ron lac 表現 -a posit ble ive width
水平居中
HTML代碼:
1 <div class="parent"> 2 <div class="child"></div> 3 </div>
1、使用margin:auto;
1 <style type="text/css"> 2 .parent{ 3 width: 600px; 4 height: 600px; 5 border: solid 1px #000000; 6 } 7 .child{ 8 width: 300px; 9 height: 300px; 10 background-color: #aa3333; 11 margin: 0 auto; 12 } 13 </style>
2、絕對定位居中;
(1)基於父元素left:50%;設定子元素margin-left為-150是需要消除父元素50%造成的偏移
CSS部分:
1 <style type="text/css"> 2 .parent{ 3 position: relative; 4 width: 600px; 5 height: 600px; 6 border: solid 1px #000000; 7 box-sizing: border-box; 8 } 9 .child{ 10 width: 300px; 11 height: 300px; 12 background-color: #aa3333; 13 position: absolute; 14 left: 50%; 15margin-left: -150px; 16 } 17 </style>
(2)子元素設置margin-left
1 .child{ 2 width: 300px; 3 height: 300px; 4 background-color: #aa3333; 5 position: absolute; 6 margin-left: 150px; 7 }
(3)父元素設置padding-left
1 .parent{ 2 position: relative; 3 width: 600px; 4 height: 600px; 5 border: solid 1px #000000; 6 box-sizing: border-box; 7 padding-left: 150px; 8 }
3、子元素設置display的表現形式inline-block;父元素文本居中
1 <style type="text/css"> 2 .parent{ 3 width: 600px; 4 height: 600px; 5 border: solid 1px #000000; 6 text-align: center; 7 } 8 .child{ 9 width: 300px; 10 height: 300px; 11 border: solid 1px #aa3333; 12 display: inline-block; 13 } 14 </style>
4、使用table表現形式,父元素display:table,子元素display:table-cell
1 <style type="text/css"> 2 .parent{ 3 width: 600px; 4 height: 600px; 5 border: solid 1px #000000; 6 display: table; 7 } 8 .child{ 9 width: 300px; 10 height: 300px; 11 border: solid 1px #aa3333; 12 display: table-cell; 13 } 14 </style>
5、flex;父元素display:flex,子元素margin:auto
1 <style type="text/css"> 2 body{ 3 padding: 0; 4 margin: 0; 5 } 6 .parent { 7 display: flex; 8 height: 300px; /* Or whatever */ 9 background-color: black; 10 } 11 .child { 12 width: 100px; /* Or whatever */ 13 height: 100px; /* Or whatever */ 14 margin: auto; /* Magic! */ 15 background-color: white; 16 } 17 </style>
垂直居中(父元素為塊級元素,高度一定)
1、子元素是行內元素
1 <div class="parent"> 2 <span>child</span> 3 </div> 4 5 <style type="text/css"> 6 body{ 7 margin: 0; 8 padding: 0; 9 } 10 .parent{height: 40px;background-color: #0bb59b;} 11 span{height: 40px;line-height: 40px;} 12 </style>
2、子元素是塊級元素,使用絕對定位
1 <div class="parent"> 2 <div class="child">child</div> 3 </div>
CSS部分
1 <style type="text/css"> 2 body{ 3 margin: 0; 4 padding: 0; 5 } 6 .parent{ 7 height: 400px; 8 background-color: #0bb59b; 9 position: relative;} 10 .child{ 11 background-color: #0b6fa2; 12 position: absolute; 13 height: 200px; 14 top: 0;right: 0; bottom: 0;left: 0; 15 margin: auto; 16 } 17 </style>
3、子元素是塊級元素,使用table表現形式
1 <div class="parent table-cell"> 2 <div class="child">child</div> 3 </div>
css部分
1 body{ 2 margin: 0; 3 padding: 0; 4 } 5 .parent{ 6 height: 400px; 7 background-color: #0bb59b; 8 display: table;} 9 .table-cell{ 10 display: table-cell; 11 vertical-align: middle; 12 } 13 .child{ 14 background-color: #0b6fa2; 15 }
CSS水平垂直居中