Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
106 views
in Technique[技术] by (71.8m points)

html - css background color with floating elements

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 <div class="right"> 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.

EDIT: here is a fiddle to test

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...