html - 为什么容器内的容器在 float 时会失去背景颜色?

标签 html css

我的“my-works”容器设置为浅灰色背景颜色。在这个容器内,有两篇文章,它们的容器名为“my-blog”和“my-game”

我将“我的博客”和“我的游戏”向左浮动,它失去了背景颜色。

为什么“my-works”(父容器)内的第二个容器(“my-blog”和“my-game”)的背景颜色与其父容器设置的背景颜色不同?

html代码

    <section class="my-works">
        <h3> MY WORKS </h3>

        <article class="my-blog">
            <h4>My Blog</h4>
            <img src="blog.png" width="45%">
        </article>

        <article class="my-game">
            <h4>A Tambay Inspired Flappy Bird - Yotni Bird</h4>
            <img src="flappybird.png" width="45%">
        </article>

    </section>

CSS 代码

    .my-works {
    width:100%;
    background-color: #F0F0F5;
        }

    .my-works h3 {
        text-align:center;
        margin-top: 0;
        padding: 20px;

        }

    .my-blog {
        width: 40%;
        float:left;


        }
    .my-game {
        width: 40%;
        float:left;


        }

这是图片

enter image description here

最佳答案

由于应用了 float ,.my-works div 将不再完全包裹内部 div。

您需要向 .my-works div 添加某种clear或clearfix

clearfix

.my-works:before,
.my-works:after { 
    content: ""; 
    display: table;
}
.my-works:after {
    clear: both;
}

或者您可以将带有 clear:both; 的标记添加到您的 html 中。

清晰

<section class="my-works">
    <h3> MY WORKS </h3>

    <article class="my-blog">
        <h4>My Blog</h4>
        <img src="blog.png" width="45%">
    </article>

    <article class="my-game">
        <h4>A Tambay Inspired Flappy Bird - Yotni Bird</h4>
        <img src="flappybird.png" width="45%">
    </article>

  <br style="clear:both">

</section>

关于html - 为什么容器内的容器在 float 时会失去背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32653247/

相关文章:

javascript - 如何在背景图片上添加文字

html - 使用VBA从网站上的表格中检索<TD>标签并放入excel

javascript - 使标题保持在一定的窗口宽度?

html - 带边距居中div :auto is not working

css - 如何垂直拉伸(stretch)颜色输入?

css - 我需要将条形排列在底部,而不是顶部

html - 如何制作只影响文本而不影响图像的 CSS 规则?

javascript - 当ajax代码工作时,使用javascript禁用html中的链接

jquery - 显示带有 fancyBox 的 youtube 视频,仅在 chrome 中启用滚动

css - R Shiny 更改 dateRangeInput 小部件的大小和格式