CSS media query is a CSS rule that allows us to apply different styles to the webpage depending on the user's device or screen size.
The following diagram shows how the layout is changed for various user devices.
The styles are applied based on the characteristics of the user's device or viewport. These characteristics can include the screen width, height, orientation, and more.
The CSS @media rule enables the creation of responsive web designs.
CSS Media Query Syntax
Here is the syntax of the media query.
Here,
- @media: keyword that specifies the beginning of a media query block
- media-type: specifies the type of media for applying the styles; common media types include all, screen, print, and speech
- media-feature-rule: defines the specific conditions to apply underlying CSS styles such as width, height, or screen orientation
Let's look at an example.
Here, the media query targets a media_type of the screen and checks the condition min-width: 768px.
If the screen width is 768 pixels or more, the enclosed CSS styles will be applied.
The value 768px is also referred to as a breakpoint.
Example: Navigation Menu Using CSS Media Query
Let's first create a navigation menu for the desktop and laptop
layout.
Browser Output
In the above example, the navigation menu looks good on desktops and laptops.
Now, to change the layout for mobile devices, we can use the media query. For example,
Browser Output
In the example above, once the device width reaches a breakpoint of 576px, the specified styles are applied, and the horizontal navigation menu transitions into a vertical menu.
In this way, media queries allow our website to appear elegant on a wide range of screen sizes.
Top comments (0)