如果我们要进行Css的布局,那float(浮动)就是最为关键的一个属性了。 浮动可以使你的块元素不遵守元素流的布局特性,如果不采用浮动,元素将一个接一个地往下排列。float属性有三个值:left、right和none, 后面我们就会使用这些值的。我们将使用事例来说明布局的特性。
我们做一个html文件,为后面的讲解准备一下:
- < body >
- < div id = "Masthead" > Masthead </ div >
- < div id = "Sidebar_a" > Sidebar_a </ div >
- < div id = "Sidebar_b" > Sidebar_b </ div >
- < div id = "Content" > Content </ div >
- < div id = "Footer" > Footer </ div >
- </ body >
这样的html使用浏览器打开一定是就几个字符把,我们先加一些简单的Css来标记,这样可以更加清楚地看到页面的布局。
- body
- {
- padding : 10px ;
- margin : 10px ;
- }
- div
- {
- border : 1px solid #000 ;
- background-color : #CCC ;
- height : 20px ;
- padding : 10px ;
- text-align :Center;
- }
- #Masthe ad
- {
- margin-bottom : 10px ;
- background-color : #CCCCCC ;
- }
- #Sideba r_a
- {
- margin-bottom : 10px ;
- background-color : #3399CC ;
- }
- #Sideba r_b
- {
- margin-bottom : 10px ;
- background-color : #33ff33 ;
- }
- #Conten t
- {
- margin-bottom : 10px ;
- background-color : #ff3366 ;
- }
- #Footer
- {
- background-color : #ffff00 ;
- }
我们给每一个Div加上了一个边框,并给每一个Div使用上背景颜色,方便标志。
上面5个Div,分别代表了网页模板里面最常见的表头、表尾、两个边栏和中间的内容。现在还没有添加更多的Css,所以还只是5个从上到下的Div 而已。我们先分析一下,首先表头Masthead和表尾Footer两部分已经基本符合要求了,不会需要做更多的改变,那就是中间的两个边栏 Sidebar和内容Content需要从左往右排列,我们先看看完成的Css和布局的样子:
- #Masthe ad
- {
- background-color : #CCCCCC ;
- margin-bottom : 10px ;
- }
- #Sideba r_a
- {
- float : left ;
- width : 25% ;
- margin-bottom : 10px ;
- background-color : #3399CC ;
- }
- #Sideba r_b
- {
- float : right ;
- width : 25% ;
- margin-bottom : 10px ;
- background-color : #33ff33 ;
- }
- #Conten t
- {
- margin-bottom : 10px ;
- height : 150px ;
- background-color : #ff3366 ;
- }
- #Footer
- {
- clear : both ;
- background-color : #ffff00 ;
- }
首先说明一下,所有的html没有作任何修改,只是添加了一些Css。
比较前面和后面的Css,Masthead和Content里面的内 容没有什么改变,Content里面的height:150px;只是为了说明内容较多情况下会是怎么样的情况。关键就是Sidebar_a内的 float:left;和Sidebar_b内的float:right;。正是这两个属性使我们的布局顺利完成了。大家还可以自己尝试一下,把 Sidebar_a和Sidebar_b内的属性换一下,两个边栏的位置就对换了,这个正体现了Div+Css布局的灵活性。
我们别忘记了在表尾Footer内有clear:both;属性,这个属性又是做什么的呢?浮动使用了以后会对后面的元素造成影响,所以要清理掉。
注意:上面的Html里面的五个Div不能顺便的变换位置,不然就不能正常地显示。特别是Content要在两个边栏的后面。
上面只是简单地说明了Div的布局,大家要熟练使用还是自己多多练习了。