CSS Media Queries
Apply styles based on viewport and user preference features.
Modern websites are viewed on many different devices, including smartphones, tablets, laptops, and large desktop screens. Since each device has a different screen size, a website needs to adapt its layout and design to provide the best user experience.
CSS Media Queries are a feature that allows developers to apply different styles based on the characteristics of a device, such as screen width, height, or orientation. Media Queries are one of the most important tools for creating responsive websites.
Why Are Media Queries Important?
Media Queries help developers:
- Create responsive layouts
- Improve mobile usability
- Adjust designs for different screen sizes
- Hide or display content when needed
- Enhance the user experience across devices
For example, a website may display three columns on a desktop screen but switch to a single column on a smartphone. Media Queries make this possible.
What Is a Media Query?
A Media Query checks a device condition and applies CSS rules only when that condition is true.
Basic Syntax
@media (max-width: 768px) {
body {
background-color: lightblue;
}
}In this example:
- The styles inside the Media Query are applied only when the screen width is 768 pixels or less.
- On larger screens, the styles are ignored.
Common Breakpoints
Breakpoints are screen sizes where the layout changes.
Some commonly used breakpoints include:
- Mobile: 480px and below
- Tablet: 768px and below
- Laptop: 1024px and below
- Desktop: Above 1024px
These values can vary depending on the design requirements.
Changing Layouts with Media Queries
Media Queries can modify layouts for smaller screens.
Example
.container {
display: flex;
}
@media (max-width: 768px) {
.container {
flex-direction: column;
}
}On larger screens, items appear side by side.
On smaller screens, items stack vertically.
Adjusting Font Sizes
Text should be easy to read on all devices.
Example
h1 {
font-size: 40px;
}
@media (max-width: 600px) {
h1 {
font-size: 28px;
}
}The heading becomes smaller on mobile devices, preventing overflow issues.
Hiding Elements
Media Queries can show or hide content based on screen size.
Example
@media (max-width: 768px) {
.sidebar {
display: none;
}
}This hides the sidebar on smaller screens to create more space for the main content.
Using Orientation Queries
Media Queries can also detect device orientation.
Example
@media (orientation: landscape) {
body {
background-color: lightgray;
}
}This style applies when the device is in landscape mode.
Key Takeaways
- Media Queries is an important topic to understand.
- Start with small examples and practice one step at a time.
- Use the idea in simple projects so it becomes easier to remember.