CSS media

CSS Media and its example

CSS Media and its example

You can apply styles based on the viewport’s or device’s specifications (such as screen size, height, or type) using CSS media queries. This is particularly helpful for creating responsive websites, which make sure they look good across a range of platforms, including PCs, tablets, and smartphones.

See Also: HTML Media and its example

Syntax

@media (media-type) and (media-feature) {
  /* CSS rules go here */
}

media-type: Indicates the kind of gadget (print, screen, etc.).
media-feature: Indicates parameters such as orientation, height, and screen width.

Example

Let’s create a responsive design that changes the background color based on screen width.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Media Query Example</title>
  <style>
    /* Default style for all devices */
    body {
      background-color: lightblue;
      font-size: 16px;
    }

    /* When the screen width is 768px or wider */
    @media (min-width: 768px) {
      body {
        background-color: lightgreen;
        font-size: 18px;
      }
    }

    /* When the screen width is 1024px or wider */
    @media (min-width: 1024px) {
      body {
        background-color: lightcoral;
        font-size: 20px;
      }
    }

    /* For printing */
    @media print {
      body {
        background-color: white;
        font-size: 12px;
      }
    }
  </style>
</head>
<body>
  <h1>Hello, Media Queries!</h1>
  <p>Resize the browser window to see the effect of media queries.</p>
</body>
</html>

Live Example

See the Pen
Untitled
by Meena Subash (@Meena-Subash-the-sasster)
on CodePen.

Explanation

1.Default styles:

All devices have a light blue backdrop with a 16px font size.

2.@media (min-width: 768px):

In viewport widths 768px and wider (usually tablets), the text size rises to 18px and the background color turns lightgreen.

3.@media (min-width: 1024px):

The background color changes to lightcoral and the font size rises to 20px for screens that are 1024 pixels wide or wider, such as desktop computers.

4.@media print:

To improve legibility on paper, the user can print the page with a white backdrop and a font size of 12px.

Commonly Used Media Features

min-width and max-width: Set styles in response to the viewport’s width.
Min-height and max-height: These styles are activated according to the viewport’s height.
orientation: Use different styles depending on whether the device is in landscape or portrait mode.
resolution: Use styles according to screen resolution; this technique is frequently applied to high-density screens, such as Retina displays.

Responsive Design Tip:

Designing for mobile devices first and gradually improving your styles for larger screens is smart practice.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top