2013-08-01 91 views
0

我不断遇到同样的问题一遍又一遍 - 浮动元素的流体div没有背景(因为它没有“高度”)。我尝试过使用:在选择器之后,甚至弥补假身高。但是这些解决方案都不是优雅或一致的。我想知道处理这个问题的最好,最适应性最强的方法。我正在寻找“这是专业人士如何做”的解决方案,我可以反复重复使用,永远不用再担心它。无高度的div背景

这是一个非常简单的jsFiddle,你可以玩。列表应该有橙色背景。从的jsfiddle http://jsfiddle.net/y4Va3/

代码:

.wrapper {background-color: blue; width: 100%;} 
.content {background-color: orange; width: 50%; margin: 0 auto;} 
.bottom {background-color: green; width: 100%; clear: both;} 
ul {margin: 0px 10px; padding: 0; float: left;} 
li {list-style-type: none;} 

<div class="wrapper"> 
    <div class="content"> 
     <ul> 
      <li>list item</li> 
      <li>list item</li> 
      <li>list item</li> 
      <li>list item</li> 
      <li>list item</li> 
     </ul> 
     <ul> 
      <li>list item</li> 
      <li>list item</li> 
      <li>list item</li> 
      <li>list item</li> 
      <li>list item</li> 
     </ul> 
    </div> 
    <div class="bottom"> 
     Not much here 
    </div> 
</div> 

感谢您的时间。

回答

1

正如大多数人所说,overflow: hidden是确保您的折叠元素获得所需高度的首选方式。下面是a nice explanation

以下属性/值组合会导致 元素建立一个新的块格式化上下文:

float: left and float: right 
display: inline-block, display: 
inline-table, display: table-cell and display: table-caption 
position: absolute and position: fixed 
overflow: hidden, overflow: auto and overflow: scroll 
    and their overflow-x and overflow-y counterparts. 

不难理解为什么溢出:隐藏(或溢出:汽车) 通常用于建立新的BFC:所有其他选项或者 通常具有非常不良的副作用,或者不受Internet Explorer 7及更低版本的支持。

所以在理论上,你可以使用任何以上,以确保您的父元素知道它里面的其他元素(它的好,但是要记住,他们都只是有的副作用创建一个新的BFC,其目的在于列出的属性显然是完全不同的)。

如果我因为某些原因无法添加overflow: hidden(例如,显示悬停时跨越父级的菜单),我经常使用的技巧是浮动父元素。在你的情况下,像这样:

.content { 
    background-color: orange; 
    width:50%; 
    margin: 0; 
    float: left; 
} 

当然,这会打破你的中心位置,并不适合在这种特殊情况下。但在不想隐藏溢出的情况下记住这一点很好。然后,您可以也良好的措施增加width: 100%,以确保您的浮动父元素模仿块级结构:)

+1

选择这个作为答案,因为它实际上有助于解释为什么这种技术有效。 –

1

定义您.contentoverflow:hidden像这样

.content { 
overflow:hidden; 
} 

Demo

=========

选项没有第二

.content:after{content:""; 
overflow:hidden; 
    clear:both; 
    display:table; 
} 

Demo2

1

试试这个Demo

http://jsfiddle.net/y4Va3/2/

.wrapper { 
    background-color: blue; 
    width: 100%; 
} 

.content { 
    background-color: orange; 
    width:50%; 
    margin: 0 auto; 
    overflow:hidden; 
} 

.bottom { 
    background-color: green; 
    width: 100%; 
    clear: both; 
} 
ul { 
    margin: 0px 10px; 
    padding: 0; 
    float: left; 
} 

li { 
    list-style-type: none; 
} 
1

尝试溢出:汽车;

.content { 
    background-color: orange; 
    width:50%; 
    margin: 0 auto; 
    overflow:auto; 
    } 

Link-demo

1

可以使用height 100%, overflow hidden

.content { 
    background-color: orange; 
    width: 50%; 
    margin: 0 auto; 
    height: 100%; 
    overflow: hidden; 
} 

jsFiddle Link

1

尝试此链接.. Demo

U需要这样的提及。

.content ul li{ 
    background-color:red; 
} 

希望这是你想要的...