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>
新闻热点
疑难解答