使用CSS属性选择器定位背景图片的src [英] Using CSS Attribute Selectors to target the src of background-image
问题描述
我正在使用background-image属性将图像分配到网站上的 div
范围。但是,使用 background-image
属性,我还需要分配 background-size
使其看起来正确。
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.
大多数情况下都可以正常工作,但是我需要根据<中使用的文件类型来更改 background-size
属性。 code>背景图片属性。例如,作为标准,我想使用 background-size:cover;
,但是当 background-image
是SVG时我想使用 background-size:auto;
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;
是否可以使用CSS属性选择器?如果没有,是否有其他解决方案?
Is this possible using CSS attribute selectors? If not, any other solution?
我的尝试(SCSS):
&.bg-image {
background-size: cover;
background-repeat: no-repeat;
background-position: center;
min-height: 500px;
max-height: 700px;
&[src$=".svg"] { background-size: auto; }
}
推荐答案
如果 background-image
是您唯一的内联CSS属性,您可以执行以下操作:
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>
如果背景图像
不是唯一的属性,但它是最后一个属性,则可以使用以下选择器: [style $ =。svg)]
。
If background-image
is not the only property but it is the last one, you can use this selector: [style$=".svg)"]
.
最后,最常见的情况是,对于样式属性中背景图像
的任何位置,请使用以下选择器: [style * =。svg)]
。
Finally, the most general case, for any location of background-image
in the style attribute use this selector: [style*=".svg)"]
.
即使使用最松散的选择器: [style * =。svg)]
(或jpg,或png ...),选择器唯一可以应用的声明就是背景图像。
Even with the loosest selector: [style*=".svg)"]
(or jpg, or png...) the only declaration the selector can possibly apply is the background-image.
另一种方法是添加 data-type = svg
或将您带到div,然后将其定位到CSS [数据类型= svg]
。
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]
.
或者您也可以使用 img
在您的示例中。
Or you could use img
instead, as in your example.
这篇关于使用CSS属性选择器定位背景图片的src的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!