为什么,当我向右浮动时,背景颜色消失了?

Ant*_*ett 1 html css

在页面底部,我想要一个黄色的横条,上面有社交媒体链接和其他小细节。我希望链接在右侧,小细节在左侧。

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>
Run Code Online (Sandbox Code Playgroud)

CSS:

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

.one-third {
    float:right;
}
Run Code Online (Sandbox Code Playgroud)

在我写这篇文章的时候,我认为 .三分之一对于 CSS 部分是不正确的,也许它应该是footer a img {...}.

更新:不,即使我这样做 ^ 它仍然摆脱了页脚的背景颜色。然后我在页脚上添加了一个 BG 颜色和一个 img 样式,它只在图标后面发生了变化,而不是整个页脚。

hun*_*tar 5

当您浮动一个元素时,您将其从当前文档流中取出。这意味着什么?好吧,就容器元素而言,那些浮动元素不占用空间。如果容器元素没有任何内容占用空间(高度),则容器的高度为 0 且没有背景颜色。即使浮动元素不占用空间,其他元素也会“看到”它们并围绕它们流动。

怎么修?清除浮动。最流行的方法是使用clearfix。clearfix 通常是一个 CSS 类。我使用Nicolas Gallagher的micro clearfix

/**
 * 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;
}
Run Code Online (Sandbox Code Playgroud)
<footer class="cf"><!-- floated elements --></footer>
Run Code Online (Sandbox Code Playgroud)

另一个 clearfix 解决方案是应用于overflow: hidden;包含浮动元素的元素。这有一些缺点,因为有时您不想隐藏溢出父级的内容。

footer {
    width: 100%;
    background-color: #f5c300;
    overflow: hidden;
}
Run Code Online (Sandbox Code Playgroud)