Home  >  Article  >  Web Front-end  >  典型的三行两列居中高度自适应div+css布局_html/css_WEB-ITnose

典型的三行两列居中高度自适应div+css布局_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 12:28:161232browse

如何使整个页面内容居中,如何使高度自适应内容自动伸缩,这是学习CSS布局最常见的问题。

 

下面给出一个实际的列子,附详细说明。

 

首先可以将下列代码复制到html文件中运行一下,在mozilla、opera和ie浏览其中,均可达到居中且自适应高度的要求。

 

body

{

       background:#999;

       text-align:center;

       color:#333;

       font-family:Arial, Verdana, Sans-serif;

}

#header

{

       width:776px;

       margin-left:auto;

       margin-right:auto;

       padding:0px;

       background:#eee;

       height:60px;

       text-align:center;

}

#container

{

       margin-left:auto;

       margin-right:auto;

       width:776px;

}

#mainbg

{

       width:776px;

       padding: 0px;

       background:#60A179;

       float:left;

}

#right

{

       float:right;

       margin:2px 0px 2px 0px;

       padding:0px;

       width:574px;

       background:#ccd2de;

       text-align:left;

}

#left

{

       float:left;

       margin:2px 2px 0px 0px;

       padding:0px;

       background:#f2f3f7;

       width:200px;

       text-align:left;

}

#footer

{

       clear:both;

       width:776px;

       margin-right:auto;

       margin-left:auto;

       padding:0px;

       background:#eee;

       height:60px;

}

.text

{

       margin:0px;

       padding:20px;

}

      

             

             

                    

left

                    

             

      

 

首先我们定义了body和顶部区域#header,这里面关键的是body中的text-align:center;以及header中的margin-left:auto和margin-right:auto;作用是似的header区域在浏览器中居中。注意:在IE中只需要定义body的text-align:center就可以居中了,但是在mozilla(firefox)中必须有margin:auto才可以。

 

接下来是left和right区域。为了是这两列也能居中,现在其外部嵌套一层container,并且设置margin:auto,道理和上面一样。这样left和right整体的也居中了。

 

你也许奇怪,问什么在container和left、right之间还有一层mainbg,这个层有什么作用呢?这个层是用来定义背景的,那么为什么不直接在container中定义背景呢,而要在多套一层呢?原因还是mozilla(firefox)在作怪(你总不希望自己做的网页在firefox和ie中显示的效果不一样吧),在ie中不需要多嵌套一层,在mozilla中,必须定义高度值才可以显示背景,但是指定高度的话,又无法实现自适应高度的要求,所以多加了一层mainbg,窍门在与mainbg这个层的float:left;这样定义,不指定高度也可以显示背景。

 

最后定义的是底部的footer层。该层的关键点在于clear:both;这句话的作用是取消footer层的浮动继承。否则,你会看到footer紧贴这header显示,还是mozilla做得怪:)

 

按说到这里就over了,可是细心的朋友会看到left和right分别嵌套了一个层,这两个层都使用了.text{margin:0px;padding:20px},这又是为什么呢?原因是mozilla和ie对于盒子模型的解释不一样,直接定义margin、padding会造成mozilla和ie中显示的不一致。所以,遇到ie和mozilla不一致的时候,往往多加一层会解决问题。

 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn