父元素:text-align:center;
div子元素:marign:0px auto;
通过在当前元素使用margin:0px auto可以实现当前元素在父元素中的水平居中效果。
通常情况下text-align:center是用作将文本水平居中的,如果让一个div水平居中,一般要使用margin:0px auto这段代码,这个对于有开发经验的前端人员没有任何问题,但初学者往往会出现使用text-align:center来实现div水平居中的情况,并且还会得出这样的结论:有的浏览器可以有的浏览器不可以。下面就看一段代码实例: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.softwhy.com/" /> <title>为什么text-align:center无法将div水平居中-蚂蚁部落</title> <style type="text/css"> div{ width:200px; height:200px; background-color:green; text-align:center; } #children{ width:100px; height:100px; background-color:red; } </style> </head> <body> <div style="text-align:center;"> <div id="children"></div> </div> </body> </html> 以上代码的初衷是想让子元素在父元素中水平居中,这个在IE7和IE7以下浏览器中是可以的,但是在IE8和和IE8以浏览器或者其他标准浏览器中是没有任何效果的。text-align:center一般是用来规定文本和内联元素的水平居中对齐,如果想要让块级水平居中对齐,一般使用margin:0px auto来实现,代码实例如下: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.softwhy.com/" /> <title>为什么text-align:center无法将div水平居中-蚂蚁部落</title> <style type="text/css"> div{ width:200px; height:200px; background-color:green; } #children{ width:100px; height:100px; background-color:red; margin:0px auto; } </style> </head> <body> <div style="text-align:center;"> <div id="children"></div> </div> </body> </html> 以上代码通过在当前元素使用margin:0px auto可以实现当前元素在父元素中的水平居中效果。
