Using CSS to change span background color has no effect

21.9k Views Asked by At

I have applied background-color: #C0C0C0; to my span element .grey_bg but the background is not changing color. Why is that?

    .grey_bg {

      width: 100%;

      background-color: #C0C0C0;

    }
<span class="grey_bg">
        <h1>Hey</h1>
    </span>

4

There are 4 best solutions below

0
On

Because it's not really valid HTML to put block-level H1 element inside span (inline element). You can either use div instead of span

.grey_bg {
    width: 100%;
    background-color: #C0C0C0;
}
<div class="grey_bg"> 
    <h1>Hey</h1>
</div>

... or make span block-level too:

span {display: block;}
.grey_bg {
    width: 100%;
    background-color: #C0C0C0;
}
<span class="grey_bg"> 
    <h1>Hey</h1>
</span>

0
On

First your markup is not correct. You can't have a block element, h3, inside an inline element, span.

But in case you want to keep that markup, you have to make the container element to behave as block. So make it as:

.grey_bg { 
width: 100%; 
background-color: #C0C0C0; 
display:block;
}
2
On

I figured out that I had to target the h1 as well in the css:

.grey_bg h1 {
    background: #C0C0C0;
}
0
On

Your code is incorrect because your span is wrapping your H tag.

You should not use span to wrap inline element's like H tag's. Instead you want the span to be inside your H tag.

The span element is the inline level generic container. It also helps to inform the structure of document, but it is used to group or wrap other inline elements and/or text, rather than block level elements. The line between the two different types might seem fairly arbitrary at first. The difference to bear in mind is the type of content, and how it would appear when written down without any styling. A div is placed around a group of block level elements—for example, to wrap a heading plus a list of links to make a navigation menu. A span wraps a group of inline elements or (most usually) plain text. The key word is “group”: if a div wraps just one block-level element, or a span just one inline element, it's being used unnecessarily. For example, check out the way the div and span elements are used in the following simple markup:

W3C

.grey_bg {
  width: 100%;
  background-color: #C0C0C0;
}
 <h1><span class="grey_bg">Hey</span></h1>