Photo by NordWood Themes on Unsplash
CSS Media Query Basics
Quickly understand CSS media queries and how to use them
Media queries are very similar to Javascript or any other programming language in that they programmatically express an if condition.
As expressed in the pseudo-code below we have a default green background which becomes red at the larger screen width
background-color: green;
if (screen is bigger than 1024 pixels)
then with CSS make the background-color: red
Now that you get the idea here we have some sample CSS code that uses a media query code:
body {
background-color: green;
}
@media (min-width: 800px){
body {
background-color: red
}
}
Media queries can be used to check many things including but not limited to
viewport width
viewport height
type of media device - is it a printer or is it a screen - for example
Mobile first and media queries
Mobile first is the idea/design that suggests we prioritize designing for mobile devices. This is a popular concept used by both Tailwind CSS and Bootstrap ( the two most popular CSS frameworks in 2023). To keep your media queries in line with this paradigm, simply use the min-width directive and only use the min-width directive. See the example below
body {
/* default green background */
background-color: green;
}
/* red background 600px and up */
@media(min-width:600px) {
body {
background-color: red;
}
}
/* purple background 800px and up */
@media(min-width:800px){
body {
background-color: purple;
}
}
Once the browser reaches a width of 800px all three CSS rules will apply but because of the order only the last rule (background color: purple) will be active.
Observe this concept in action here: https://codepen.io/fieldsmarshall/pen/ExGLWGe
Hiding Content with Media Queries
Another common use of media queries is to hide content using the display:none CSS directive.
Dark mode using media queries
Media queries are a powerful tool in CSS for applying styles based on certain conditions. One application is to detect whether a user has set their preferences to dark mode on their device or browser, and then apply a corresponding dark theme to your webpage. The prefers-color-scheme
media feature is used for this purpose. Below are a few quick examples:
Detection of Color Scheme Preference:
- Best Practice Use the
prefers-color-scheme
media feature in a media query to check if the user has a preference for a dark or light color scheme.
- Best Practice Use the
@media (prefers-color-scheme: dark) {
/* styles for dark mode */
}
@media (prefers-color-scheme: light) {
/* styles for light mode */
}
Define Dark and Light Mode Styles:
- Within the curly braces
{ }
of each media query, define the styles that should be applied for dark mode and light mode respectively. This could be as simple as setting different background and text colors, or more complex styling adjustments.
- Within the curly braces
@media (prefers-color-scheme: dark) {
body {
background-color: #121212;
color: white;
}
}
@media (prefers-color-scheme: light) {
body {
background-color: white;
color: black;
}
}
Fallback Styles:
- It’s also a good practice to define a default set of styles outside of the media queries, to act as a fallback in case the
prefers-color-scheme
media feature is not supported or if the user has not set a preference.
- It’s also a good practice to define a default set of styles outside of the media queries, to act as a fallback in case the
body {
background-color: white;
color: black;
}
With these steps, you can set up basic detection of dark mode preferences using media queries, and provide a more comfortable viewing experience for your users. As you get more comfortable with media queries, you can explore more complex styling adjustments to better accommodate dark mode preferences.
https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme
Testing Media Queries Programmatically
Testing media queries programmatically can be done in several ways depending on the environment and the tools at your disposal. Here are some common methods used to test media queries programmatically:
JavaScript:
- You can use the
window.matchMedia()
method in JavaScript to test whether a particular media query matches the current state of the document.
- You can use the
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
if (mediaQuery.matches) {
// Media query matches
console.log('User prefers dark mode');
} else {
// Media query does not match
console.log('User does not prefer dark mode or preference is unknown');
}
// You can also add an event listener to respond to changes
mediaQuery.addEventListener('change', (event) => {
if (event.matches) {
// The media query now matches
console.log('User prefers dark mode');
} else {
// The media query no longer matches
console.log('User does not prefer dark mode or preference is unknown');
}
});
Automated Testing with a Framework:
- If you are using an automated testing framework like Jest, you might leverage a library such as
jest-matchmedia-mock
to mock and test media queries.
- If you are using an automated testing framework like Jest, you might leverage a library such as
import MatchMediaMock from 'jest-matchmedia-mock';
let matchMedia;
beforeEach(() => {
matchMedia = new MatchMediaMock();
});
// ...
test('matches dark mode media query', () => {
matchMedia.useMediaQuery('(prefers-color-scheme: dark)');
// Now, your test environment behaves as if the media query matches
// ...
});
CSS Testing Libraries:
- Libraries such as "CSSOM" or "jsdom" can be used to simulate a DOM environment and inspect computed styles as a result of media queries. You can then write assertions based on the computed styles to verify the effect of your media queries.
const { JSDOM } = require('jsdom');
const dom = new JSDOM(`<!DOCTYPE html><p>Hello world</p>`, {
pretendToBeVisual: true,
media: '(prefers-color-scheme: dark)',
});
// Now you can inspect computed styles as a result of your media queries
These are some of the methods you can use to test media queries programmatically either in the browser or in an automated testing environment. Each method has its own set of considerations, so choose the one that fits your needs and the technologies you are working with.
In the end, the best resource for learning about media queries would be the mozilla documentation https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_media_queries/Testing_media_queries or https://www.w3schools.com/css/css3_mediaqueries.asp