html - 是否可以将 CSS @media 规则内联?

标签 html css media-queries

我需要将横幅图片动态加载到 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/

相关文章:

javascript - 需要在联系表单中刷新包含验证码的 div,而不必刷新整个页面

html - Bootstrap面板定位

html - 如何修复 bootstrap 对齐文本列中的空格?

css - Node.js 不提供 css 文件

html - Div 不会像它们应该的那样折叠 - 媒体查询

java - 如何在java中获取url html内容到字符串

jquery - 将输入值打印到不同的 DIVS- jQuery

javascript - Bootstrap 下拉菜单不适用于移动设备

jquery - 将 jquery 应用于单个媒体查询

css - 我什么时候需要 *-device-width?