@media rule

The @media rule allows set style depending from media type and its features. There are CSS libraries like Bootstrap 5 that make this kind of work easier.

<link rel="stylesheet" media="screen and (min-width: 900px)" href="/css/widescreen.css">
<link rel="stylesheet" media="screen and (max-width: 320px)" href="/css/smallscreen.css">

<style>
@media print {
  body { font-size: 10pt; }
}

@media screen {  
  body { font-size: 13px; } 
}

@media screen, print {
  body { line-height: 1.2; }
}

@media screen 
  and (min-width: 320px) 
  and (max-width: 480px)
  and (resolution: 150dpi) {
    body { line-height: 1.4; }
}
<!-- media query lvl 4 -->
@media (height > 600px) {
    body { line-height: 1.4; }
}

@media (400px <= width <= 700px) {
    body { line-height: 1.4; }
}
</style>

Media Queries 4:

  1. The logical operators not, and and or can be used to compose a complex media query. Comma can be used as or operator. Keyword only is deprecated.
  2. You can use improved syntax for define range of value via relational operators.

media types

Only followed types are allowed in Media Queries 4. And types like tv now are deprecated.

device description
all This is default value, means all types of media devices.
print Printing devices.
screen Screen of computer, tablets, smart-phones etc.
speech Screen reader that allows you to read the page out loud.

features

Some features can be prefixed with max- and min-. For example, aspect-ratio, min-aspect-ratio, max-aspect-ratio.

feature description
height The viewport height.
width The viewport width.
aspect-ratio Represents the width-to-height aspect ratio of the viewport.
@media (min-aspect-ratio: 8/5) {
  div {  background: #00f;  }
}
resolution Test the pixel density of the output device.
@media (resolution: 150dpi) {
  p { color: red; }
}
orientation Test the orientation of the viewport. Possible values are:
  • portrait - the viewport is in a portrait orientation ( height >= width)
  • landscape - the viewport is in a landscape orientation (width >= height)
any-hover Checks is device has input mechanism allowing user to hover over elements. Possible values are:
  • hover - user can hover over elements
  • none - user can't hover over elements
any-pointer Tests whether the user has any pointing device. Possible values are:
  • none - no pointing device is available.
  • coarse - at least one pointing device available with limited accuracy
  • fine - at least one accurate pointing device available
color Test the number of bits per color component (red, green, blue) of the output device.
/* Any color device */
@media (color) { p { color: red; } }

/*minimum 8 bit per pixel */
@media (min-color: 8) { p { color: red; } }
color-index Tests the number of entries in the output device's color lookup table.