我需要将横幅图片动态加载到 HTML5 应用程序中,并且想要几个不同的版本以适应屏幕宽度。我无法正确确定手机的屏幕宽度,所以我能想到的唯一方法是添加 div 的背景图像并使用 @media 确定屏幕宽度并显示正确的图像。
例如:
<span style="background-image:particular_ad.png; @media (max-width:300px){background-image:particular_ad_small.png;}"></span>
这可能吗,或者有人有任何其他建议吗?
最佳答案
@media
at 规则和媒体查询不能存在于内联样式属性中,因为它们只能包含 property: value
声明。作为the spec说:
The value of the style attribute must match the syntax of the contents of a CSS declaration block
仅在特定媒体中将样式应用于特定元素的唯一方法是在样式表中使用单独的规则(它在外部或内部链接在 <style>
元素中),这意味着您需要想出它的选择器。你可以抢一个using your browser's dev tools ,或找出隔离此元素的类和/或 ID 组合:
#myelement { background-image: url(particular_ad.png); }
@media (max-width: 300px) {
#myelement { background-image: url(particular_ad_small.png); }
}
如果由于页面的性质而无法单独找到可靠匹配此元素的选择器,则可以使用自定义属性,前提是您无需担心特异性 or Internet Explorer :
:root { --particular-ad: url(particular_ad.png); }
@media (max-width: 300px) {
:root { --particular-ad: url(particular_ad_small.png); }
}
<span style="background-image: var(--particular-ad);"></span>
关于html - 是否可以将 CSS @media 规则内联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37320043/