Caspert Caspert - 3 months ago 7
CSS Question

Why does css cover not working on "parent" div?

I have a class that will be used by multiple DOM elements, of course..
I created the class

.highlight
and to each highlight div, I added an unique
id
to it.

.highlight {
height: 520px;
width: 100%;
padding: 0;
display: table;
overflow: hidden;
border: none;
}
.highlight#pixel {
background: url('../images/pixel.jpg') no-repeat center;
}


Each ID has it's own
background-image
via css. I would like to use the css property
background: cover;
to fill in all space with the image.

I thought it would work if you added the cover property to the div
.highlight
, because the id is added to the same div and so I don't have to add the cover property every time to each id in the css, but this doesn't work. Any thoughts why this is not working.

I speak about the following:

.highlight {
height: 520px;
width: 100%;
padding: 0;
display: table;
overflow: hidden;
border: none;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
.highlight#pixel {
background: url('../images/pixel.jpg') no-repeat center;
}


Thnx!

Answer
background: url('../images/pixel.jpg') no-repeat center;

This is overwriting the background-size rule in the previous, less specific selector .highlight. Instead of using the shorthand in .highlight#<id>, you could use it to set background defaults on all .highlight elements, then be specific when declaring the image, for example:

.highlight {
  ...
  background: no-repeat center / cover;
}

.highlight#pixel {
  background-image: url('../images/pixel.jpg');
}