[html] Is it possible to put CSS @media rules inline?

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.

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?

This question is related to html css media-queries

The answer is


if you add the rule to the print.css file you don't have to use @media.

I uncluded it in the smarty foreach i use to give some elements a background color.

_x000D_
_x000D_
<script type='text/javascript'>_x000D_
  document.styleSheets[3].insertRule(" #caldiv_<?smarty $item.calendar_id ?> { border-color:<?smarty $item.color ?> }", 1);_x000D_
</script>
_x000D_
_x000D_
_x000D_


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);">

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 style markup and not the attribute.

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

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.

Note : the scoped attribute 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.


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>

Hey I just wrote it.

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

Enjoy.


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

You can use style elements with appropriate media attributes in head section of your document.


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.

<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


Inline media queries are possible by using something like Breakpoint for Sass

This blog post does a good job explaining how inline media queries are more manageable than separate blocks: There Is No Breakpoint

Related to inline media queries is the idea of "element queries", a few interesting reads are:

  1. Thoughts on Media Queries for Elements
  2. Media Queries are a Hack
  3. Media Queries Are Not The Answer: Element Query Polyfill
  4. if else blocks

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.

<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>

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.

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.


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

  1. desktop for red colour text

  2. tablet for green colour text

  3. mobile for blue colour text

_x000D_
_x000D_
//isat_style_media_query_for_desktop_mobile_tablets_x000D_
var tablets = window.matchMedia("(max-width:  768px)");//for tablet devices_x000D_
var mobiles = window.matchMedia("(max-width: 480px)");//for mobile devices_x000D_
var desktops = window.matchMedia("(min-width: 992px)");//for desktop devices_x000D_
_x000D_
_x000D_
_x000D_
isat_find_device_tablets(tablets);//apply style for tablets_x000D_
isat_find_device_mobile(mobiles);//apply style for mobiles_x000D_
isat_find_device_desktops(desktops);//apply style for desktops_x000D_
// isat_find_device_desktops(desktops,tablets,mobiles);// Call listener function at run time_x000D_
tablets.addListener(isat_find_device_tablets);//listen untill detect tablet screen size_x000D_
desktops.addListener(isat_find_device_desktops);//listen untill detect desktop screen size_x000D_
mobiles.addListener(isat_find_device_mobile);//listen untill detect mobile devices_x000D_
// desktops.addListener(isat_find_device_desktops);_x000D_
_x000D_
 // Attach listener function on state changes_x000D_
_x000D_
function isat_find_device_mobile(mob)_x000D_
{_x000D_
  _x000D_
// isat mobile style here_x000D_
var daynight=document.getElementById("daynight");_x000D_
daynight.style.color="blue";_x000D_
_x000D_
// isat mobile style here_x000D_
_x000D_
}_x000D_
_x000D_
function isat_find_device_desktops(des)_x000D_
{_x000D_
_x000D_
// isat mobile style here_x000D_
_x000D_
var daynight=document.getElementById("daynight");_x000D_
daynight.style.color="red";_x000D_
 _x000D_
//  isat mobile style here_x000D_
}_x000D_
_x000D_
function isat_find_device_tablets(tab)_x000D_
{_x000D_
_x000D_
// isat mobile style here_x000D_
var daynight=document.getElementById("daynight");_x000D_
daynight.style.color="green";_x000D_
_x000D_
//  isat mobile style here_x000D_
}_x000D_
_x000D_
_x000D_
//isat_style_media_query_for_desktop_mobile_tablets
_x000D_
    <div id="daynight">tricky style for mobile,desktop and tablet</div>
_x000D_
_x000D_
_x000D_


If you are using Bootstrap Responsive Utilities or 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.

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

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to media-queries

iPhone X / 8 / 8 Plus CSS media queries What is correct media query for IPad Pro? How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript? CSS media query to target only iOS devices How to set portrait and landscape media queries in css? iPhone 6 and 6 Plus Media Queries Responsive design with media query : screen size? Bootstrap 3 breakpoints and media queries $(window).width() not the same as media query How to make responsive table