CSS Media Query Basics
Quickly understand CSS media queries and how to use them

Search for a command to run...
Quickly understand CSS media queries and how to use them

No comments yet. Be the first to comment.
Encrypting your .env file in a Node.js project helps protect sensitive environment variables, such as API keys and database URLs, especially when sharing code or deploying applications. This approach allows you to keep these details secure while stil...

An Introduction of key concepts, terms and ideas related to typography on the web using CSS

Review of the most important units for measuring in CSS.

The color wheel, CSS and Sir Isaac Newton

4 types of CSS Combinators explained with examples

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 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
Another common use of media queries is to hide content using the display:none CSS directive.
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:
prefers-color-scheme media feature in a media query to check if the user has a preference for a dark or light color scheme. @media (prefers-color-scheme: dark) {
/* styles for dark mode */
}
@media (prefers-color-scheme: light) {
/* styles for light mode */
}
Define Dark and Light Mode Styles:
{ } 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. @media (prefers-color-scheme: dark) {
body {
background-color: #121212;
color: white;
}
}
@media (prefers-color-scheme: light) {
body {
background-color: white;
color: black;
}
}
Fallback Styles:
prefers-color-scheme media feature is not supported or if the user has not set a preference. 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 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:
window.matchMedia() method in JavaScript to test whether a particular media query matches the current state of the document. 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:
jest-matchmedia-mock to mock and test media queries. 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:
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