CSS

Media Queries rule and breakpoints


What are Media Queries?

Media queries are used in CSS to apply different styles for different devices or screen sizes. This helps create responsive web designs that look good on all devices, from desktops to smartphones.

 

@media Rule

The @media rule is used to define media queries in CSS. It applies styles based on the result of one or more media features, such as screen width, height, orientation, etc.

 

Example

<!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 - Codersmile</title>
    <style>
        body {
            background-color: lightblue;
        }

        @media (max-width: 600px) {
            body {
                background-color: lightcoral;
            }
        }
    </style>
</head>
<body>
    <h1>Welcome to Codersmile</h1>
    <p>This is an example of using media queries.</p>
</body>
</html>

In this example, the background color of the page will change to light coral if the screen width is 600 pixels or less.

 

Breakpoints

Breakpoints are specific screen widths at which the layout of the webpage changes. These are used in conjunction with media queries to make the design responsive.

 

Common Breakpoints

  • Extra small devices (phones): max-width: 600px
  • Small devices (tablets): max-width: 768px
  • Medium devices (small laptops): max-width: 992px
  • Large devices (desktops): max-width: 1200px

 

Example with Breakpoints

Here’s an example using common breakpoints:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Breakpoint Example - Codersmile</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
        }

        h1 {
            font-size: 24px;
        }

        @media (max-width: 1200px) {
            body {
                background-color: lightgray;
            }
        }

        @media (max-width: 992px) {
            body {
                background-color: lightblue;
            }

            h1 {
                font-size: 22px;
            }
        }

        @media (max-width: 768px) {
            body {
                background-color: lightgreen;
            }

            h1 {
                font-size: 20px;
            }
        }

        @media (max-width: 600px) {
            body {
                background-color: lightcoral;
            }

            h1 {
                font-size: 18px;
            }
        }
    </style>
</head>
<body>
    <h1>Welcome to Codersmile</h1>
    <p>This is an example of using media queries with breakpoints.</p>
</body>
</html>

In this example:

  • The background color and font size of the h1 tag will change based on the screen width.
  • The styles are applied according to different breakpoints, making the page responsive.