Tech Junkie Blog - Real World Tutorials, Happy Coding!: Target Specific Media Environments With CSS Media And Feature Queries

Tuesday, August 6, 2019

Target Specific Media Environments With CSS Media And Feature Queries

If you use media queries in CSS you can target a specific media with a stylesheet.  It is defined by the media attribute in the link tag.

The possible media values are the following:

  • all - all presentation media
  • print - used for display print and print preview
  • screen - all screens that uses the browser user agents
Here are a few examples:

<link type="text/css" href="print_media.css" media="print">
<link type="text/css" href="style.css" media="all">
<link type="text/css" href="screen_media.css" media="screen">

Or you can have multiple media types like this

<link type="text/css" href="screen_media.css" media="screen,print">

If you want to do it inline you can use by typing in the following:

<style type="text/css" media="screen">h1 {color:red;}</style>

Inside the stylesheets itself the media blocks has a @ prefix in front of it like so, you can have as many as you want.

@media all {
       h1 {color:red;}

@media screen,print{
      h2 {color: black;}

The cool thing about media queries is that you can apply some simple logic to the application of it for instance let's say you only want to use the style only if the screen meets a certain requirement you can say

@media all and (min-resolution: 300dpi) { }
@media screen not (orientation: landscape) {}

You can also use media queries to make older browsers ignore your new styles by using the @import directive.

Let's say you have styles.css stylesheet, but you also have the new styles in the new_styles.css file.  You only want to apply the stylesheet new_styles.css in browsers that understands media queries.  So in the styles.css stylesheet you have have the first line be @import url(new_styles.ccss) only all  only browsers that understands media queries will apply the stylesheet while the old browsers will ignore it.

The other queries you can use which is similar to media queries are feature queries.  As the name implies a feature querie apply a style only if the user agent supports the feature.

To implement a feature querie you would do something like this, if you want a block of style to only be applied if the grid layout is supported.

@supports (display:grid){}

You can also combine a support querie and a media querie, like so

@supports (display:flex){
        @media screen { }

You can also use the and and not condition in feature queries as well, there's even an or

@supports (color: red) and (display:flex) or (display:grid) { }

No comments:

Post a Comment

Search This Blog