Introduction to media queries
What is Media Queries?
Media queries are CSS rules that allow you to apply styles conditionally based on specific characteristics of the device or environment where the webpage is being viewed. These characteristics can include:
- Screen size: This is the most common use case, allowing you to define different styles for different screen widths (e.g., desktops, tablets, mobiles).
- Device orientation: You can create separate styles for portrait and landscape modes on mobile devices.
- Resolution: Media queries can target devices with high-resolution (Retina) displays.
- Other factors: Media queries can also target specific media types like print or screen, user preferences like reduced motion, or even the presence of a pointer (mouse vs. touchscreen).
Using Media Queries
Media queries are written using the @media rule in CSS. The basic syntax is:
@media (media_type) and (media_feature) { /* Styles to apply when the condition is met */}- @media: This keyword introduces the media query.
- media_type: This specifies the type of media being targeted (e.g., screen, print). Often omitted, it defaults to all.
- media_feature: This defines the specific characteristic to check (e.g., (min-width: 768px), targeting screens wider than 768px).
- {}: This block contains the CSS styles that will be applied when the media query condition is true.
Example:
/* Styles for all screens */body { font-family: Arial, sans-serif; font-size: 16px;}
/* Styles for screens wider than 768px */@media (min-width: 768px) { body { font-size: 18px; } .content { width: 70%; margin: 0 auto; /* Center the content horizontally */ }}
/* Styles for screens narrower than 768px */@media (max-width: 767px) { .content { width: 100%; /* Make content full width on small screens */ }}In this example, we have a base style for all screens. Then, we use media queries to adjust the font size and layout for larger and smaller screens.
Benefits of Media Queries:
- Targeted Styles: Media queries allow you to apply styles specifically to different screen sizes, creating a more optimal viewing experience for each device.
- Flexible Layouts: By using media queries, you can create fluid layouts that adapt and rearrange elements based on the available space.
- Improved Maintainability: Media queries keep your CSS code organized and easier to manage, as styles for different screen sizes are separated.
By mastering media queries, you can unlock the full potential of responsive design and ensure your websites deliver a seamless user experience across all devices.