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; }
}
CSS [attribute|="value"] Selector The [attribute|="value"] selector is used to select elements with the specified attribute, whose value can be exactly the specified value, or the specified value followed by a hyphen (-).
To do so, we can combine the attribute selector with the adjacent sibling selector, +. The snippet above will target every image with the source attribute ending with . jpg , then the adjacent selector will find the element next to it. In this case the figcaption will be added with the #a8b700 background color.
CSS [attribute~=value] Selector The [attribute~=value] selector is used to select elements with an attribute value containing a specified word.
The background-image CSS property sets one or more background images on an element.
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-image
is 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With