最近开始尝试Web标准,不可避免的就遇到了DIV的居中问题。
在网上搜了一通,有用DIV嵌套的,有用脚本的,不过都不理想。
最后发现网友Charlee这个方法效果不错:
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
这里要注意的是,margin-left、margin-top的值必须分别设为width和height值的一半。
页面效果如下图所示:
![](http://tech.idv2.com/wp-content/uploads/2007/07/centered-div.png)
原文地址:http://tech.idv2.com/2007/07/22/center-div-horizontally-and-vertically-with-css/
此方法可同时实现水平、垂直两个方向的居中,如果只要求水平方向的居中,可以这样写:
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
第一行指定DocType的语句必不可少,否则有些新的CSS特性不会生效。
我在自己测试的时候忘记了加这一句,结果导致Div如何也不水平居中——后来才醒悟到是这个在作怪,加上后马上就正常了。
还有,width的值是必须给出的,而height可以不用,因为只是要求水平方向居中。
如果不嫌麻烦的话,margin那一句也可用这个来代替:
margin-left:auto;
margin-right:auto;
margin-right:auto;
以上CSS经过本人测试,完全可用。
却原来、姹紫嫣红开遍,似这般、都付与断井颓痕 ——《昆曲·游园惊梦》