Introduction:
Media queries offer a powerful means to adapt our styles based on factors such as the device type, viewport size, screen pixel density, or device orientation.
For those already familiar with media queries, this post serves as a quick guide, unveiling some clever tricks that might not be widely known.
Fundamental Media Queries:
Media queries are constructed using the @media at rule, incorporating a media type, zero or more media features, or a combination of both a media type and media feature(s). The permissible media types include all, print, screen, and speech. If not explicitly mentioned, the type “all” is assumed.
It is possible to employ multiple media types simultaneously, with each type separated by commas:
In the following simple example, the default background color is red, but screen devices with a viewport width that’s 650px or less will have a background color of blue instead:
Example of simple media queries that specify either a media type, a media feature or both:
Utilizing Multiple Media Features:
To meet specific requirements in a media query, you can designate multiple media features by employing the logical operator “and” between them. When utilizing “and,” the query will only be a match if all the features evaluate to true:
Using the “or” Logical Operator:
By defining multiple queries separated by commas, you introduce logical “or” operators. The media query then transforms into a list of queries, applying if any of the comma-separated queries matches the conditions.
In the example below, the media query holds true if the device’s viewport has a minimum width of 2rem or a maximum aspect ratio of 4/1:
Employing the “not” Logical Operator:
By placing “not” at the beginning of a query, you can achieve the opposite effect. This is particularly useful for applying styles when the browser or device fails to meet specific conditions. An example scenario is when the primary pointing device lacks the ability to hover over elements.
When employing “not,” it’s essential to specify the media type. Additionally, it’s crucial to note that “not” applies to each individual query and not to an entire list of queries separated by commas. Each query within the list is subject to the “not” condition independently.
Exclusive Use of the “only” Logical Operator:
The “only” logical operator holds a unique characteristic—it conceals the entire query for older browsers. In simpler terms, older browsers that do not comprehend the “only” keyword will ignore the entire media query. Otherwise, the “only” keyword itself has no impact on the query’s behavior.