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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9808233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 23:16:45  来源:igfitidea点击:

Is it possible to put CSS @media rules inline?

htmlcssmedia-queries

提问by Dancer

I need to dynamically load banner images into a HTML5 app and would like a couple of different versions to suit the screen widths. I can't correctly determine the phone's screen width, so the only way I can think of doing this is to add background images of a div and use @media to determine the screen width and display the correct image.

我需要将横幅图像动态加载到 HTML5 应用程序中,并希望有几个不同的版本来适应屏幕宽度。我无法正确确定手机的屏幕宽度,因此我能想到的唯一方法是添加 div 的背景图像并使用@media 确定屏幕宽度并显示正确的图像。

For example:

例如:

 <span style="background-image:particular_ad.png; @media (max-width:300px){background-image:particular_ad_small.png;}"></span>

Is this possible, or does anyone have any other suggestions?

这是可能的,或者有人有任何其他建议吗?

采纳答案by BoltClock

No, @mediarules and media queries cannot exist in inline style attributes as they can only contain property: valuedeclarations. As the specputs it:

不,@media内联样式属性中不能存在规则和媒体查询,因为它们只能包含property: value声明。正如规范所说:

The value of the style attribute must match the syntax of the contents of a CSS declaration block

style 属性的值必须与 CSS声明块内容的语法匹配

The only way to apply styles to an element only in certain media is with a separate rule in your stylesheet, which means you'll need to come up with a selector for it.

将样式应用于特定媒体中的元素的唯一方法是在样式表中使用单独的规则,这意味着您需要为它提供一个选择器。

A dummy spanselector would look like this, but if you're targeting a very specific element you will need a more specific selector:

一个虚拟span选择器看起来像这样,但如果你的目标是一个非常具体的元素,你将需要一个更具体的选择器:

span { background-image: url(particular_ad.png); }

@media (max-width: 300px) {
    span { background-image: url(particular_ad_small.png); }
}

回答by Bruno Lesieur

Problem

问题

No, Media Queries cannot be used in this way

不,不能以这种方式使用媒体查询

<span style="@media (...) { ... }"></span>

Solution

解决方案

But if you want provided a specific behavior usable on the fly AND responsive, you can use the stylemarkup and not the attribute.

但是,如果您想提供可即时使用style且响应的特定行为,则可以使用标记而不是属性。

e.i.

<style scoped>
.on-the-fly-behavior {
    background-image: url('particular_ad.png'); 
}
@media (max-width: 300px) {
    .on-the-fly-behavior {
        background-image: url('particular_ad_small.png');
    }
}
</style>
<span class="on-the-fly-behavior"></span>

See the code working in live on CodePen

查看在 CodePen 上实时运行的代码

In my Blog for example, I inject a <style>markup in <head>just after <link>declaration for CSS and it's contain the content of a textarea provided beside of real content textarea for create extra-class on the fly when I wrote an artitle.

例如,在我的博客中,我<style>在CSS 声明<head>之后注入了一个标记<link>,它包含在真实内容 textarea 旁边提供的 textarea 的内容,以便在我编写 atitle 时即时创建额外的类。

Note : the scopedattribute is a part of HTML5 specification. If you do not use it, the validator will blame you but browsers currently not support the real purpose : scoped the content of <style>only on immediatly parent element and that element's child elements. Scoped is not mandatory if the <style>element is in <head>markup.

注意:该scoped属性是 HTML5 规范的一部分。如果你不使用它,验证器会责怪你,但浏览器目前不支持真正的目的:<style>仅将内容限定在直接父元素和该元素的子元素上。如果<style>元素在<head>标记中,Scoped 不是强制性的。



UPDATE: I advice to always use rules in the mobile first way so previous code should be:

更新:我建议始终以移动优先方式使用规则,因此以前的代码应该是:

<style scoped>
/* 0 to 299 */
.on-the-fly-behavior {
    background-image: url('particular_ad_small.png'); 
}
/* 300 to X */
@media (min-width: 300px) { /* or 301 if you want really the same as previously.  */
    .on-the-fly-behavior {   
        background-image: url('particular_ad.png');
    }
}
</style>
<span class="on-the-fly-behavior"></span>

回答by Marat Tanalin

Inline styles cannot currently contain anything other than declarations (property: valuepairs).

内联样式当前不能包含除声明(property: value对)以外的任何内容。

You can use styleelements with appropriate mediaattributes in headsection of your document.

您可以在文档的部分中使用style具有适当media属性的元素head

回答by Arif Hussain

Yes, you can write media query in inline-css if you are using a picture tag. For different device sizes you can get different images.

是的,如果您使用的是图片标签,您可以在 inline-css 中编写媒体查询。对于不同的设备尺寸,您可以获得不同的图像。

<picture>
    <source media="(min-width: 650px)" srcset="img_pink_flowers.jpg">
    <source media="(min-width: 465px)" srcset="img_white_flower.jpg">
    <img src="img_orange_flowers.jpg" alt="Flowers" style="width:auto;">
</picture>

回答by Pavel

If you are using Bootstrap Responsive Utilitiesor similar alternative that allows to hide / show divs depending on the break points, it may be possible to use several elements and show the most appropriate. i.e.

如果您使用Bootstrap Responsive Utilities或允许根据断点隐藏/显示 div 的类似替代方案,则可以使用多个元素并显示最合适的。IE

 <span class="hidden-xs" style="background: url(particular_ad.png)"></span>
 <span class="visible-xs" style="background: url(particular_ad_small.png)"></span>

回答by Type-Style

Media Queries in style-Attributes are not possible right now. But if you have to set this dynamically via Javascript. You could insert that rule via JS aswell.

现在无法在样式属性中进行媒体查询。但是,如果您必须通过 Javascript 动态设置它。您也可以通过 JS 插入该规则。

document.styleSheets[0].insertRule("@media only screen and (max-width : 300px) { span { background-image:particular_ad_small.png; } }","");

This is as if the style was there in the stylesheet. So be aware of specificity.

这就像样式在样式表中一样。所以要注意特异性。

回答by Даниил Пронин

Hey I just wrote it.

嘿,我刚写的。

Now you can use <div style="color: red; @media (max-width: 200px) { color: green }">or so.

现在你可以使用<div style="color: red; @media (max-width: 200px) { color: green }">左右。

Enjoy.

享受。

回答by davidcondrey

I tried to test this and it did not seem to work but I'm curious why Apple is using it. I was just on https://linkmaker.itunes.apple.com/us/and noticed in the generated code it provides if you select the 'Large Button' radio button, they are using an inline media query.

我试图对此进行测试,但它似乎没有用,但我很好奇 Apple 为何使用它。我刚刚在https://linkmaker.itunes.apple.com/us/ 上并注意到在它提供的生成代码中,如果您选择“大按钮”单选按钮,他们正在使用内联媒体查询。

<a href="#" 
    target="itunes_store" 
    style="
        display:inline-block;
        overflow:hidden;
        background:url(#.png) no-repeat;
        width:135px;
        height:40px;
        @media only screen{
            background-image:url(#);
        }
"></a>

note: added line-breaks for readability, original generated code is minified

注意:为了可读性添加了换行符,原始生成的代码被缩小

回答by the7oker

You can use image-set()

您可以使用图像集()

<div style="
  background-image: url(icon1x.png);
  background-image: -webkit-image-set(  
    url(icon1x.png) 1x,  
    url(icon2x.png) 2x);  
  background-image: image-set(  
    url(icon1x.png) 1x,  
    url(icon2x.png) 2x);">

回答by ??l?j?

yes,you can do with javascript by the window.matchMedia

是的,您可以通过window.matchMedia使用 javascript

  1. desktop for red colour text

  2. tablet for green colour text

  3. mobile for blue colour text
  1. 红色文本的桌面

  2. 绿色文本的平板电脑

  3. 用于蓝色文本的移动设备

//isat_style_media_query_for_desktop_mobile_tablets
var tablets = window.matchMedia("(max-width:  768px)");//for tablet devices
var mobiles = window.matchMedia("(max-width: 480px)");//for mobile devices
var desktops = window.matchMedia("(min-width: 992px)");//for desktop devices



isat_find_device_tablets(tablets);//apply style for tablets
isat_find_device_mobile(mobiles);//apply style for mobiles
isat_find_device_desktops(desktops);//apply style for desktops
// isat_find_device_desktops(desktops,tablets,mobiles);// Call listener function at run time
tablets.addListener(isat_find_device_tablets);//listen untill detect tablet screen size
desktops.addListener(isat_find_device_desktops);//listen untill detect desktop screen size
mobiles.addListener(isat_find_device_mobile);//listen untill detect mobile devices
// desktops.addListener(isat_find_device_desktops);

 // Attach listener function on state changes

function isat_find_device_mobile(mob)
{
  
// isat mobile style here
var daynight=document.getElementById("daynight");
daynight.style.color="blue";

// isat mobile style here

}

function isat_find_device_desktops(des)
{

// isat mobile style here

var daynight=document.getElementById("daynight");
daynight.style.color="red";
 
//  isat mobile style here
}

function isat_find_device_tablets(tab)
{

// isat mobile style here
var daynight=document.getElementById("daynight");
daynight.style.color="green";

//  isat mobile style here
}


//isat_style_media_query_for_desktop_mobile_tablets
    <div id="daynight">tricky style for mobile,desktop and tablet</div>