2013-02-09 119 views
1

这是我的代码奇怪的行为漂浮

#sidebar 
{ 
    width:140px; 
    border: solid 3px green; 
    height:300px; 
    float:left; 
} 


#content 
{ 
    border: solid 3px blue; 
    height:400px; 
    float:left; 

} 
<div id="sidebar">Sidebar</div> 

<div id="content">Content</div> 

由于未指定内容div的宽度,如预期它会占用足够的空间显示在div内的文本

现在,而是采用浮动我使用保证金是这样的:

#content 
{ 
    border: solid 3px blue; 
    height:400px; 
    margin-left:160px; 

} 

即使未指定宽度,内容div现在也将占用浏览器视口的其余宽度

我认为这样做的原因是content div继承了用户代理样式表分配的body标签的width属性。如果这是真的,我的问题是为什么当我使用浮动不是继承发生?

回答

0

div默认未指定的widthwidth:100%;

您需要指定width:auto;才能获得所需的效果,只有足够宽才能包含其内容。

#content 
{ 
    width : auto; 
    border : solid 3px blue; 
    height : 400px; 
    float : left; 
}