实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>盒模型</title> <style> .box1 { margin:10px 20px 30px 40px; padding: 10px 20px 30px 40px; width: 500px; height: 200px; background-color: lightblue; text-align: center; } .box1 span { line-height: 200px; } .box2 { width: 500px; height: 200px; background-color: lightpink; display: table-cell; text-align: center; vertical-align: middle; } .box3 { width: 400px; height: 400px; background-color: #aaa; display: table-cell; vertical-align: middle; } .box3 .box4 { width: 200px; height: 200px; background-color: lime; margin: auto; } .box5{ width: 600px; height: 140px; text-align: center; display: table-cell; vertical-align: middle; background-color: wheat; } .box5 ul { padding: 0; margin: 0; } .box5 li { list-style-type: none; display: inline; padding: 0 10px; } #demo div { width: 150px; height: 150px; background-color: coral; } #demo div:nth-of-type(odd) { background-color: green; } #demo div:nth-of-type(1) { position: relative; left: 150px; } #demo div:nth-of-type(2) { position: relative; left: 150px; } #demo div:nth-of-type(3) { position: relative; top: -150px; background-color: skyblue; } #demo div:nth-of-type(4) { position: relative; left: 150px; top: -150px; background-color: brown; } #demo div:nth-of-type(5) { position: relative; left: 300px; top: -450px; background-color: lawngreen; } </style> </head> <body> <!-- 子元素为单行行内元素时,通过父级中text-align:center来设置水平居中,行内子元素中设置行高line-height与父元素等高可设置垂直居中 --> <div class="box1"><span>padding简写方式顺序为:up,right,bottom,left</span></div> <!-- 子元素为多行行内元素时,通过父级中text-align:center来设置水平居中,设置父元素的display:table-cell及vertical-align:middle来实现垂直居中 --> <div class="box2"><span>margin简写方式顺序为:<br>up,right,bottom,left</span></div> <br> <div class="box3"><div class="box4">子元素为块元素时,设置子元素左右外边距自适应margin:auto,设置父元素display:table-cell及vertical-align:middle来实现垂直居中</div></div> <br> <!-- 子元素为不定宽的块元素时,在父级中text-align:center来设置水平居中,设置父元素的display:table-cell及vertical-align:middle来实现垂直居中 --> <div class="box5"> <ul> <li><a href="">第1项</a></li> <li><a href="">第2项</a></li> <li><a href="">第3项</a></li> <li><a href="">第4项</a></li> <li><a href="">第5项</a></li> </ul> </div> <hr> <h1>用五个色块制作一个十字(使用相对定位)</h1> <div id="demo"> <div class="item1"></div> <div class="item2"></div> <div class="item3"></div> <div class="item4"></div> <div class="item5"></div> </div> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例