The @media CSS Rule

The @media CSS rule allows different styles to be applied to different media.

Media Types

As listed below, there are various media types that the @media CSS rule can be applied to:

 

The code below shows an example of the @media CSS rule being applied to screen and print.

@media screen 
{
   p 
   {
      font-size: 14px;
      background-colour:red;
   }
}

@media print 
{
   p
   {
      font-size: 11px;
      background-colour:none;
   }
}

@media screen, print
{
   font-family:"Times New Roman", Georgia, Serif;
}

Logical Operators

There are three logical operators:

Media Features

The most commonly used media features are:

The full set of media features can be seen here.

Many of the media features - including width and height - can be prefixed with min- or max- to express minimum or maximum constraints. This allows us to create a range of values to match instead of having to declare specific values.

Media Queries

The @media CSS rule combines media type, logical operators and media features to form media queries.

Media queries are used to customize the appearance of websites for multiple devices. Media queries are a fundamental part of responsive web design, as they enable webpage content to adapt to different screen sizes.

We can add AND, NOT, and , (OR) logical operators to an @media CSS rule, as shown below:

@media mediaType logicalOperators (mediaFeature) 
{
    CSS-Code;
}

For example, code below will only apply to screen devices that have a maximum width of 400px:

@media screen AND (max-width:400px) 
{
   body 
   {
      background-color:red;
   }
}

It is extremely difficult to specify the size of every device. Instead, we specify five general device sizes:

Small phones
@media screen AND (max-width:600px)
Large phones and small tablets
@media screen AND (min-width:601px) AND (max-width:768px)
Tablets
@media screen AND (min-width:769px) AND (max-width:992px)
Laptops
@media screen AND (min-width:993px) AND (max-width:1200px)
Large desktop monitors
@media screen AND (min-width:1201px)

Printing

We can control how a webpage should appear when it is being printed. The two most useful printing styles are:

Both of these usually use the always property

For example:

.pageBreak
{ 
  page-break-before:always
}

To attach this style to a particular instance of (for example) a <h1> tag, use the code below:

<h1 class=pageBreak>

To attach the same style to a particular instance of a <p> tag, use the code below:

<p class=pageBreak>
 
<div align="center"><a href="../../versionC/index.html" title = "DKIT Lecture notes homepage for Derek O&#39; Reilly, Dundalk Institute of Technology (DKIT), Dundalk, County Louth, Ireland. Copyright Derek O&#39; Reilly, DKIT." target="_parent" style='font-size:0;color:white;background-color:white'>&nbsp;</a></div>