Cover Image for CSS @Media Query
118 views

CSS @Media Query

CSS @media queries are a powerful feature that allows you to apply different CSS styles based on the characteristics of the user’s device or viewport. Media queries are commonly used for responsive web design, enabling you to create layouts that adapt to different screen sizes and devices.

The syntax for using @media queries is as follows:

@media media-type and (media-feature) {
  /* CSS rules to apply when the media feature matches */
}
  • media-type: Specifies the type of media the query is targeting. It is optional and is often omitted. The most common media types are all (default), screen (for computer screens), print (for printers), speech (for screen readers), etc.
  • media-feature: Defines the specific characteristics of the media you want to target. For example, the max-width or min-width media features are often used for responsive design to adjust styles based on the width of the viewport.

Here’s an example of using a media query to apply different styles for screens with a maximum width of 768 pixels:

/* Styles for screens with a width of 768 pixels or less */
@media screen and (max-width: 768px) {
  body {
    font-size: 16px;
  }

  .container {
    width: 90%;
    margin: 0 auto;
  }
}

In this example, the @media screen and (max-width: 768px) media query targets screens with a maximum width of 768 pixels. When the screen width matches the specified condition, the styles inside the media query block will be applied.

With media queries, you can adjust font sizes, layouts, spacing, and other CSS properties to create a responsive design that adapts to various devices, such as smartphones, tablets, laptops, and desktops. This helps ensure a better user experience and readability on different screen sizes and resolutions.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS