margin: 0px auto与居中

  • Post author:
  • Post category:其他


代码如下


.cen {
margin: 0px auto;
border: 1px red solid;
}
</style>
</head>
<body>
<div class="cen">aaa</div>
</body>

[img]http://dl.iteye.com/upload/picture/pic/122396/c58d815b-cd30-33ca-8caf-c9b63c1d90db.jpg[/img]

发现div并没有居中显示,原因是它的width没有设置,默认值为auto.

而CSS规范中说

If ‘width’ is set to ‘auto’, any other ‘auto’ values become ‘0’ and ‘width’ follows from the resulting equality.

见[url]http://www.w3.org/TR/CSS2/visudet.html#Computing_widths_and_margins[/url]

我猜它的意思是如果width是auto,那么其他的auto会设为0,然后width设为最大宽度.

PS: follows from the resulting equality.真心理解不了….

所以上面那个例子中,div没居中显示.

解决方法要看究竟是想div居中,还是div里面的字居中

div居中


.cen {
margin: 0px auto;
border: 1px red solid;
width: 300px;
}

[img]http://dl.iteye.com/upload/picture/pic/122398/86f0c1f5-1446-3628-8cd0-5fe207054766.jpg[/img]

div的内容居中


.cen {
margin: 0px auto;
border: 1px red solid;
text-align: center;
}

[img]http://dl.iteye.com/upload/picture/pic/122400/181e8c27-510e-3d7a-a84a-769122a06a7b.jpg[/img]