CSS设置块元素水平垂直居中
作者:不烦恼 发布时间:August 24, 2011 分类:开心上网
很简单,但用的时候总是想不起来:
<!doctype html> <html> <head> <meta charset="utf-8"> <style type="text/css"> #cm { height:200px; width:400px; margin:-100px 0px 0px -200px; padding:0; position:absolute; top: 50%; left: 50%; } </style> </head> <body> <header> <hgroup> </hgroup> <nav> </nav> </header> <section> <div id="cm"> </div> </section> <aside> </aside> <footer> </footer> </body> </html>
喔喔,使用了 HTML5的标准格式。
水平居中,用 margin:0 auto; 应该可以了吧.
垂直居中,相对值,也不错喔:
top: 50%;
left: 50%;
margin:-100px 0px 0px -200px;上 右 下 左,这个像素大小怎么来确定的呢?看不懂。
哈哈,原来我也一时也迷糊,后来看了下,这个大小就是靠这个块元素大小来设定的。
height:200px; /*高度200*/
width:400px; /*宽度400*/
margin:-100px 0px 0px -200px; /*向上偏移100(高度的50%)向左偏移200(宽度的50%)*/
margin:-100px 0px 0px -200px; 在这里有没有用?后面 top 和 left 定位了。
有用,而且非常重要
top 和left可以看成是将块元素左上角定位在了中心
所以需要用负边距再分别左移和上移块元素宽度和高度的50%