css与浮动元素的背景颜色 [英] css background color with floating elements

查看:169
本文介绍了css与浮动元素的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有这个非常简单的场景。

 < div class =content> 
< div class =left>
< p>一些内容< / p>
< / div>
< div class =right>
< p>一些内容< / p>
< / div>
< / div>

< div class =content>
< div class =left>
< p>一些内容< / p>
< / div>
< div class =right>
< p>一些内容< / p>
< / div>
< / div>

这是样式:

  .content {
width:960px;
height:auto;
margin:0 auto;
background:red;
clear:both;
}

.left {
float:left;
height:300px;
background:green;
}

.right {
float:right;
background:yellow;
}

事情是...当我添加内容时,父div,我们需要看到红色背景...事情是,我看不到红色背景填充所有的高度。



任何想法?



感谢一吨先进。



EDIT: 这里有一个小提琴要测试

解决方案

子元素是浮动的,它们被从文档的流中取出。在这样做时,父母不再具有定义的维度,因为孩子在技术上不占据空间。因此,父元素在自身上折叠。



在这个例子中,我们可以通过添加 overflow:hidden 到父元素,因此强制它包含children元素。或者 overflow:auto 也可以工作。有些人可能会建议它比 overflow:hidden 更好,因为你将能够判断是否有任何计算结果。



jsFiddle示例

  .content {
overflow:hidden;
}

现在父元素不再折叠,红色背景是可见的。 / p>

如果您在旧版浏览器中寻求支持,您也可以使用修复程序,但我不建议这样做。


Let's say we have this very simple scenario

 <div class="content">
    <div class="left">
       <p>some content</p>
    </div>
    <div class="right">
       <p>some content</p>
    </div>
 </div>

 <div class="content">
    <div class="left">
       <p>some content</p>
    </div>
    <div class="right">
       <p>some content</p>
    </div>
 </div>

And this is the styling:

 .content {
    width: 960px;
    height: auto;
    margin: 0 auto;
    background: red;
    clear: both;
 }

 .left {
     float: left;
     height: 300px;
     background: green;
 }

 .right {
     float: right;
     background: yellow;
 }

And the thing is... when I add content to it should pull down the parent div, and we need to see the red background... the thing is, I cannot see the red background fill all the height.

Any ideas???

Thanks a ton in advanced.

EDIT: here is a fiddle to test

解决方案

When the children elements are floated, they are taken out of the flow of the document. In doing so, the parent no longer has defined dimensions, as the children aren't technically occupying space. Thus, the parent element collapses upon itself. The same thing occurs when absolutely positioning the children elements too.

In this instance, we can fix it by adding overflow:hidden to the parent element, thus forcing it to contain the children elements. Alternatively overflow:auto works just as well. Some may suggest it is even better than overflow:hidden as you will be able to tell if any calculations are off.

jsFiddle example

.content {
    overflow:hidden;
}

Now the parent element is no longer collapsed and the red background is visible.

You could alternatively use a clearfix if you are looking for support in older browsers, but I don't recommend doing so.

这篇关于css与浮动元素的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆