Home >Web Front-end >CSS Tutorial >Why Do Non-Media Queries Sometimes Override Media Queries in CSS?
Media Queries vs. Non-Media Queries: Understanding CSS Specificity
In CSS, media queries are utilized to apply styles based on device screen size or other viewport characteristics. However, it's often observed that media queries appear to have lower priority compared to regular CSS declarations.
Reason for Lower Priority
This behavior stems from the concept of CSS cascade. When multiple rules target the same element, the browser prioritizes the rules based on their specificity. Selectors with a higher specificity will override those with lower specificity.
Media queries do not inherently enhance the specificity of selectors. Therefore, if a non-media query selector and a media query selector have the same specificity, the non-media query selector will take precedence when the media query is irrelevant.
Example:
Consider the following CSS snippet:
.logo img { width: 100%; } @media screen and (min-width: 100px) and (max-width: 1499px) { .logo img { width: 120%; } }
In this example, the non-media query rule defines a default width of 100% for the logo image. However, when the screen width falls within the specified range, the media query is activated and sets the width to 120%.
However, if the screen width is outside this range, the non-media query rule will take precedence, overriding the media query's width setting.
Solutions to Increase Priority
To elevate the priority of media queries:
Swap the Order of Rulesets:
Increase Selector Specificity:
Use !important (Caution):
The above is the detailed content of Why Do Non-Media Queries Sometimes Override Media Queries in CSS?. For more information, please follow other related articles on the PHP Chinese website!