Anthony Hulett Anthony Hulett - 5 months ago 9
CSS Question

Why, when I float right, the background color disappears?

At the bottom of the page, I would like a yellow bar to go across and have social media links and other small details. I want the links to be on the right and small details to be on the left.

HTML:

<footer>

<div class="one-third">


</div>

<div class="one-third">


</div>

<div class="one-third">

<a href="#"><img src="images/facebook.svg" />
</a>

</div>

</footer>


CSS:

footer {
width: 100%;
background-color: #f5c300;

}

.one-third {

float:right;

}


As I was writing this, I figured that the .one-third is incorrect for the CSS part and maybe it should be
footer a img {...}
.

Update: No even as I did this ^ it still got rid of the background color of the footer. I then threw a BG color on the footer a img style and it only changed behind the icon, not the whole footer.

Answer

When you float an element you take it out of the current document flow. What does that mean? Well, as far as container elements are concerned those floated elements don't take up space. If the container element doesn't have any content taking up space (height), then the height of the container is 0 and no background color. Even though floated elements don't take up space, other elements will "see" them and flow around them.

How to fix? Clear the float. The most popular method is to use a clearfix. A clearfix is typically a CSS class. I use the micro clearfix by Nicolas Gallagher.

/**
 * For modern browsers
 * 1. The space content is one way to avoid an Opera bug when the
 *    contenteditable attribute is included anywhere else in the document.
 *    Otherwise it causes space to appear at the top and bottom of elements
 *    that are clearfixed.
 * 2. The use of `table` rather than `block` is only necessary if using
 *    `:before` to contain the top-margins of child elements.
 */
.cf:before,
.cf:after {
    content: " "; /* 1 */
    display: table; /* 2 */
}

.cf:after {
    clear: both;
}

/**
 * For IE 6/7 only
 * Include this rule to trigger hasLayout and contain floats.
 */
.cf {
    *zoom: 1;
}
<footer class="cf"><!-- floated elements --></footer>

Another clearfix solution is to apply overflow: hidden; to the element containing floated elements. This has some drawbacks as sometimes you don't want to hide content that overflows the parent.

footer {
    width: 100%;
    background-color: #f5c300;
    overflow: hidden;
}