Overview
CSS media queries not only look for the screen size to determine which styles to apply, but also look at the user’s device type and its capabilities.
Media queries are used to deliver styles customized for desktops, laptops, tablets, and phones to give the user the best possible experience on each. Often something that looks and works great on a desktop device needs to be altered to provide the same or a similar experience on a smaller or mobile device.
Media queries can be used to determine many things about the device the user is viewing the site on:
- Viewport width and height
- Orientation of the device (is the tablet/phone in landscape or portrait mode)
- Screen resolution
The following shows a set of rules used for the desktop and laptop screen sizes.
body {
font-size: 14px;
}
#main {
width: 75%;
}
#sidebar {
width: 25%;
}
Adjusting for Tablets or Smaller Desktops
But on a tablet you may want to change some of these things, such as making the sidebar slightly wider so the content doesn’t get crushed and look crowded.
What this does is look for screens between 768px and 1366px (inclusively) and applies the following styles in place of those above. It was still keep the body font size as the same since there isn’t a replacement rule in the media query.
@media screen and (min-width: 768px) and (max-width: 1366px) {
#main {
width: 65%;
}
#sidebar {
width: 35%;
}
}
Adjusting for Small Mobile (phones)
And then again, we would write another media query for small media such as phones. The following looks for screen sizes smaller than 768px and applies a new set of rules.
In this case, we want both the #main section and #sidebar section to take up the full width of the device, with the #sidebar now dropping underneath the #main section. This makes things look less crowded due to a phone screen being fairly narrow. We also increase the font size to make everything more readable in an outdoor environment.
@media screen and (max-width: 767px) {
body {
font-size: 18px;
}
#main {
width: 100%;
}
#sidebar {
width: 100%;
}
}
Note
These are extremely simplistic examples of providing media queries for smaller devices. There are many other and BETTER things that could be done while building your site and testing on multiple screen sizes and devices.
To get a more detailed description with more examples of media queries, check out the resource page on the @media rule.
CSS Notes:
- The “inherit”, “initial” and “unset” keywords can be used with any CSS property to set its value
- In CSS there are many ways to express a color value in a property
We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.