实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> /*子元素是单行行内元素*/ #one1{ width: 200px; height: 200px; background-color: #0eabff; /*设置水平居中*/ text-align: center; } #one2{ /*设置垂直居中*/ line-height:200px; } /*---------------------------------------------------------------*/ #two2{ width: 200px; height: 200px; background-color: #ff5456; /*设置水平居中*/ text-align: center; /*设置垂直居中*/ display: table-cell; vertical-align: middle; } /*---------------------------------------------------------------*/ /*子元素是块元素*/ #three1{ width: 200px; height: 200px; background-color: #ffe332; /*垂直居中*/ display: table-cell; vertical-align: middle; } #three2 { width: 100px; height: 100px; background-color: #98fff3; /*水平居中*/ margin: auto; } /*---------------------------------------------------------------*/ /*子元素是不定宽的块元素*/ #four1{ width: 200px; height: 200px; background-color: #23ff0c; /*2,设置水平居中*/ text-align: center; /*3,设置垂直居中方法二*/ display: table-cell; vertical-align: middle; } #four1 ul li{ /*1,先设置为行内元素*/ display: inline; /*设置垂直居中方法一*/ line-height: 200px; } </style> <body> <div id="one1"> <span id="one2">这是span标签</span> </div> <hr /> <div id="two2"> <span>这是span标签</span><br> <span>这是span标签</span> </div> <hr /> <div id="three1"> <div id="three2"></div> </div> <hr /> <div id="four1"> <ul style="margin: 0;padding: 0;"> <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> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例