CSS media queries
Created By: chatGPT
CSS Media Queries are an essential feature in responsive web design. They allow you to apply different styles based on the device's characteristics, such as its width, height, orientation, and resolution. This helps ensure that your website looks great on all devices, from mobile phones to desktop computers.
@media only screen and (max-width: 600px) {
body {
background-color: lightblue;
}
}
You can combine multiple media features in a single query to target specific screen sizes and styles. For example, you can set different styles for landscape and portrait orientations as well.
@media only screen and (max-width: 800px) and (orientation: portrait) {
.container {
padding: 20px;
}
}
Using media queries effectively can drastically improve user experience. Consider using breakpoints based on your design rather than specific device sizes, as more devices with varying dimensions are constantly being released.
@media only screen and (min-width: 601px) and (max-width: 1200px) {
.sidebar {
display: block;
}
}
For high-resolution displays, you can also use the
resolution
media feature. This is particularly useful for images or graphics that should look sharp on Retina or similar high-DPI screens.@media only screen and (min-resolution: 2dppx) {
img {
content: url('high-res-image.png');
}
}
Lastly, always test your media queries across different devices and browsers to ensure consistent styling. Tools like the Chrome DevTools device emulator can be incredibly helpful for this purpose.
/* Example of a basic reset for media queries */
@media all {
h1, h2, h3, p {
margin: 0;
padding: 0;
}
}