CSS的居中有水平居中和垂直居中,這兩種居中又分為行內元素居中和塊級元素居中,不同的居中用不同方法。
水平居中
1、行內元素水平居中(文本,圖片)
給父層設置 text-align:center; 可以實現行內元素水平居中。
<!DOCTYPE HTML>
<html lang=”en-US”>
<head>
<meta charset=”UTF-8″>
<title></title>
<style type=”text/css”>
.center{text-align:center;}
</style>
</head>
<body>
<div class=”center”>
<a href=”http://huoche.7234.cn/images/jb51/kdzm1c4zsmf.jpg” width=”248″ height=”162″ alt=””/>
</div>
</body>
</html>
2、確定寬度塊級元素水平居中
確定寬度的塊級元素水平居中,常用的有 margin:0 auto; 相信很多開發人員都用的是這個,不過本人認為還有更好的寫法:margin-left:auto;margin-right:auto; 因為 margin-top 和 margin-bottom 在重置 css 時就已經寫了為 0 了。
<!DOCTYPE HTML>
<html lang=”en-US”>
<head>
<meta charset=”UTF-8″>
<title></title>
<style type=”text/css”>
.center{width:100px;height:100px;margin-left:auto;margin-right:auto;background:green;}
</style>
</head>
<body>
<div class=”center”></div>
</body>
</html>
3、不確定寬度的塊級元素水平居中
不確定寬度的塊級元素有三種方法實現。
方法一:
<!DOCTYPE HTML>
<html lang=”en-US”>
<head>
<meta charset=”UTF-8″>
<title></title>
<style type=”text/css”>
*{margin:0;padding:0;}
ul{list-style:none;}
table{margin-left:auto;margin-right:auto;}
.demo li{float:left;display:inline;margin-right:5px;}
.demo a{float:left;width:20px;height:20px;text-align:center;line-height:20px;background:#316ac5;color:white;border:1px solid #316ac5;text-decoration:none;}
.demo a:hover{background:white;color:#316ac5;}
</style>
</head>
<body>
<table>
<tbody>
<tr>
<td>
<ul class=”demo”>
<li><a href=”#”>1</a></li>
</ul>
</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td>
<ul class=”demo”>
<li><a href=”#”>1</a></li>
<li><a href=”#”>2</a></li>
新聞熱點
疑難解答