dungey_140 dungey_140 - 1 month ago 9
CSS Question

Using CSS Attribute Selectors to target the src of background-image

I am using using the background-image attribute to assign images to a range of

div
on my site. However, with
background-image
attributes, I also need to assign
background-size
to get it looking right.

This works fine mostly, but I need to change the
background-size
attribute based on the file type used in the
background-image
attribute. For example, as standard I want to user
background-size: cover;
but when the
background-image
is an SVG I want to use
background-size: auto;


Is this possible using CSS attribute selectors? If not, any other solution?

My attempt (SCSS):

&.bg-image {
background-size: cover;
background-repeat: no-repeat;
background-position: center;
min-height: 500px;
max-height: 700px;
&[src$=".svg"] { background-size: auto; }
}

Answer

If background-image is your only inline CSS property, you can do this:

.bg-image {
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
    min-height: 300px;
    max-height: 700px;
}

.bg-image[style^="background-image:"][style$=".svg)"] {
  background-size: 103px 94px;
}
<div class="bg-image" style="background-image: url(https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg)"></div>

If background-imageis not the only property but it is the last one, you can use this selector: [style$=".svg)"].

Finally, the most general case, for any location of background-image in the style attribute use this selector: [style*=".svg)"].

Even with the loosest selector: [style*=".svg)"] (or jpg, or png...) the only declaration the selector can possibly apply is the background-image.

The other approach is to add data-type=svg or what have you to the divs and then target them in CSS [data-type=svg].

Or you could use img instead, as in your example.

Comments