div居中css样式写法

作者:分开不是尽头 | 创建时间: 2023-08-04
多个div居中的css样式的写法有很多,但是,可能出现浏览器不兼容问题,关于布局,是做网页的最重要的部分,所以要有好的布局。...
div居中css样式写法

操作方法

像这样的多个div要怎么居中呢: <div id="header">header</div> <div id="sidebar">sidebar</div> <div id="news">news</div> <div id="about">about</div> <div id="estate">estate</div> <div id="footer">footer</div>

要实现居中,可以这样来,一个一个来,为每个div加上这样的css:margin:0 auto;但这种方法比较笨,所以建议采用下面的方法。

也可以这样来,把中间四个做成一个div: <div id="header">header</div> <div> <div id="sidebar">sidebar</div> <div id="news">news</div> <div id="about">about</div> <div id="estate">estate</div> </div> <div id="footer">footer</div> 然后通过浮动实现,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不用嵌套,保持不变,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;才可以。

温馨提示

布局很重要,是网页的基础,所以学习的时候要认真,多看别人怎么布局的,都是应用了什么方法。
写css要注意浏览器兼容问题,解决兼容不要想得太复杂,有时候加一句css就可以了,但也不能想得太简单,有时候可能要重写。
点击展开全文

更多推荐