简体   繁体   中英

Why does my list's background-color disappear when I float its list elements?

The moment I float my unordered-list element...the background color fails. Why?

<style type="text/css">

    .bkgrd-blue { background-color: #094AB2; }

    .application-bar { color: #FFFFFF; }

    .application-bar ul { }
    .application-bar ul.control-bar { list-style: none outside none; margin: 0; overflow: visible; padding: 0; }

    .application-bar ul.control-bar.branding { float: left;}
</style>

<div class="application-bar bkgrd-blue">
    <ul class="control-bar">
        <li>
            This is working!
        </li>
    </ul>
</div>

<div class="application-bar bkgrd-blue">
    <ul class="control-bar branding">
        <li>
            The moment I float this...it fails! Why?
        </li>
    </ul>
</div>

Floating an element removes it from the normal document flow so containers don't expand - that is, the containing div has 0 height.

To fix this you need to clear the float. You can either:

  • set overflow: hidden on the div
  • float the div
  • add an element after the floated list with clear:both - this could be done using the :after pseudo-element

Here's a demo using the first solution: http://jsfiddle.net/FSH4Y/

I added:

.application-bar {
    color: #FFFFFF;
    overflow: hidden;
}

Here's some more info on this issue: CSS Tricks: All About Floats - have a look at the section called The Great Collapse

You need to clear under the list, usually I add a div like

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

This will allow the floated element's parent to properly calculate it's height.

You need to float the containing div with the background in it as well. As soon as you float the inner ul, the containing div effectively has no content so ends up with a height of 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM