CSS Media Queries

Media queries are used to control the presentation of a web page based on the viewing environment. For example, you can use media queries to change the layout of your web page for different screen sizes, or to change the font size for different resolutions.

The @media Rule

Media queries are written using the @media rule. The @media rule is followed by a comma-separated list of media queries. Each media query is a set of conditions that must be met for the CSS rules that follow the media query to be applied.

For example, the following media query will apply the following CSS rules to all devices with a width of at least 600 pixels:

@media (min-width: 600px) {
  .my-element {
    width: 50%;
  }
}

Media Query Types

There are three main types of media queries:

  • Screen: Screen media queries are used to target devices with screens, such as laptops, desktops, and tablets.
  • Print: Print media queries are used to target printers.
  • Resolution: Resolution media queries are used to target devices with different resolutions, such as high-definition (HD) and standard-definition (SD) devices.

Media Query Operators

Media queries can use a variety of operators to combine multiple conditions. The following operators are supported:

  • and: All conditions must be met.
  • or: At least one condition must be met.
  • not: The condition must not be met.

For example, the following media query will apply the following CSS rules to all devices with a width of at least 600 pixels and a height of at least 400 pixels:

@media (min-width: 600px) and (min-height: 400px) {
  .my-element {
    width: 50%;
  }
}

Task

To make the portfolio responsive copy past the below code. Run the code and experiment with the code to get used to it.

@media screen and (max-width: 600px) {
    header img {
        float: none; /* Remove float */
        margin-right: 0;
    }

    /* Adjust font size for smaller screens */
    header h1 {
        font-size: 24px;
    }
}

Conclusion

Media queries are a powerful tool for creating responsive web pages that look good on all devices. By understanding how media queries work, you can create web pages that are accessible to everyone.

Here are some tips for using media queries:

  • Use media queries to create layouts that are fluid and responsive.
  • Use media queries to change the font size for different resolutions.
  • Use media queries to add or remove elements from the page for different screen sizes.
  • Use media queries to target specific devices, such as tablets or phones.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT