多个div居中的css样式的写法有很多,但是,可能出现浏览器不兼容问题,关于布局,是做网页的最重要的部分,所以要有好的布局。
工具/原料
1
div
2
css
方法/步骤
1
像这样的多个div要怎么居中呢:
header
news
about
estate
2
要实现居中,可以这样来,一个一个来,为每个div加上这样的css:margin:0 auto;但这种方法比较笨,所以建议采用下面的方法。
3 然后通过浮动实现,css可以这样写:div{ margin:0 auto;}#header{ height:323px; background:green; }#sidebar{ height:490px; background:pink; float:left;}#news{ height:300px; background:lightgreen; float:left;}#about{ height:300px; background:navy; float:left; }#estate{ height:190px; background:#666; float:left;}#footer{ clear:both; height:110px; background:#ccc; }
也可以这样来,把中间四个做成一个div:
header
news
about
estate
4
还可以这样来,div不用嵌套,保持不变,css这样:body{ margin:0 auto;}#header{height:323px;background:green;}#sidebar{height:490px;background:pink;float:left;}#news{height:300px;background:lightgreen;float:left;}#about{height:300px;background:navy;float:left;}#estate{height:190px;background:#666;float:left;}#footer{clear:both;height:110px;background:#ccc;}但要设置body的宽度和header、footer的宽度相同,其他四个的和宽度也要等于body设置的宽度,还有,这种方法在很多浏览器都可以正常居中,但在IE不能正常实现居中,要在body加上:text-align:center;才可以。
注意事项
1
布局很重要,是网页的基础,所以学习的时候要认真,多看别人怎么布局的,都是应用了什么方法。
2
写css要注意浏览器兼容问题,解决兼容不要想得太复杂,有时候加一句css就可以了,但也不能想得太简单,有时候可能要重写。
下一篇:CSS行高的设置(27)