I'm working on a responsive site where each page will have a large hero image, defined in the CMS. I'd like to avoid having to download that background image on mobiles.
The only way I can think to do it is to have some inline CSS in the head of the page like so:
<style type="text/css">
@media only screen and (min-width: 680px) {
.hero-image { background-image: url(../images/image.jpg); }
}
</style>
First, can I use media queries in inline CSS?
Second, will this avoid downloading the image on mobiles?
Third, is there a better way?
Thanks
Solution with the internal style It is not possible to use CSS @media rules and media queries in the inline style attribute as it can only contain property: value pairs. According to the W3 specification, the style attribute's value should match the syntax of contents of a CSS declaration block.
Important: Always put your media queries at the end of your CSS file.
Media queries are useful when you want to modify your site or app depending on a device's general type (such as print vs. screen) or specific characteristics and parameters (such as screen resolution or browser viewport width).
CSS Media queries are a way to target browser by certain characteristics, features, and user preferences, then apply styles or run other code based on those things. Perhaps the most common media queries in the world are those that target particular viewport ranges and apply custom styles, which birthed the whole idea of responsive design.
Yes, you may use media queries in a <style> tag. The image is only loaded if the CSS requires it to be, so if nothing matches the selector then it won't bother loading the image. It would probably be better to include the media query in your external CSS file, though. There's no reason to include it inlline. 313k 77 448 575 Thanks.
However, by default, a general media query declaration applies to all three media types so there is no need to specify a media type unless the aim is to exclude one or more of them. A media query is a CSS property; it can, therefore, only be used within the styling language.
No, @media rules and media queries cannot exist in inline style attributes as they can only contain property: value declarations. As the spec puts it: 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.
Yes, you may use media queries in a <style>
tag. The image is only loaded if the CSS requires it to be, so if nothing matches the selector then it won't bother loading the image.
It would probably be better to include the media query in your external CSS file, though. There's no reason to include it inlline.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With