Maira Maira - 5 months ago 13
CSS Question

CSS Background styling does not work when styling elements within a section

I have a section that I want to have a specific background color for. It works fine when I don't style the article element within in, but i 'disappears' when I do.
This is the HTML:

<section id="news">
<article>
<h3>News Item #1</h3>
<p>This is a paragraph.</p>
<a href="#">Read More</a>
</article>
<article>
<h3>News Item #2</h3>
<p>Place any important lines</p>
<a href="#">Read More</a>
</article>
</section>


So I added this CSS to do change the background:

#news {
background: #5D9B4C;
max-width: 900px;
margin-top: 30px;
}


And it works. However when I try to style the article within the news section, the background color from the whole section goes away.

#news article {
float: left;
width: 280px;
margin-left: 20px;
margin-bottom: 30px;
}


Is there a reason why this happens?

Thanks so much in advance.

Answer

That's all about floating. There are a lot of techniques to achieve correct result.

Recommend to investigate All About Floats.

For example:

   #news {
     background: #5D9B4C;
     overflow: hidden;
   }
   
   #news article {
     float: left;
     width: 50%;
   }
<section id="news"> 
    <article> 
        <h3>News Item #1</h3>
        <p>This is a paragraph.</p>
        <a href="#">Read More</a>
    </article>
    <article> 
        <h3>News Item #2</h3>
        <p>Place any important lines</p>
        <a href="#">Read More</a>
    </article>
</section>