2012-05-03 18 views
1

我有这样的代码:我必须设置容器的高度吗?

#container { 
    position:relative; 
    width:760px;  

    margin-left: auto; 
    margin-right: auto; 
    margin-top: 10px; 

    border: 1px solid #cdcdcd; 
} 

#sidebar { 
    float:left; 
    width: 200px; 
    background:red; 
} 

#wrapper { 
    float:left; 
    width:460px; 
background:blue; 

}

和HTML代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 

    <head> 
     <title>Example.com</title> 
     <link rel="stylesheet" type="text/css" href="style.css"/> 
    </head> 
    <body> 
     <div id="container"> 
      <div id="sidebar"> 
         LEFT 
      </div> 

      <div id="wrapper"> 
       RIGHT 
      </div>   
     </div> 
    </body> 
</html> 

我看到容器没有高度....我必须设置呢?我想解释高度取决于内部DIV的高度,我怎么能做到这一点?

回答

4

您没有设置高度,只需添加:

<div style="clear: both;"></div> 

正下方,你任何浮动的div。


在你的情况,你可以这样做:

只需添加到你的CSS文件。

.clear { 
    clear: both; 
} 

和更新您的HTML文件,以匹配

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 

    <head> 
     <title>Example.com</title> 
     <link rel="stylesheet" type="text/css" href="style.css"/> 
    </head> 
    <body> 
     <div id="container"> 
      <div id="sidebar"> 
         LEFT 
      </div> 

      <div id="wrapper"> 
       RIGHT 
      </div>  
      <div class="clear"></div>  
     </div> 
    </body> 
</html> 
+0

谢谢!如果我不使用它,它不会遵循内部DIV的高度,因为它无法理解在末尾是否有其他元素? – Dail

+2

@Dail浮动元素从文档流中移除,因此不会影响父母的“身高”。 'clear:both'告诉div在这里恢复正常的文档流程,并允许它识别高度 –

1

那是因为你使用float:left。一个解决办法是增加一个clear:both股利如下:

CSS:

.clear { 
    clear: both; 
} 

HTML:

<div id="container"> 
    <div id="sidebar">LEFT</div> 
    <div id="wrapper">RIGHT</div> 
    <div class="clear"></div> 
</div> 
0

给容器中的额外的CSS

overflow: hidden; 

这将打破浮动没有额外的标记
(不会工作w ith box-shadow)