In my App.js I have the following imports:
import React from 'react'
import './styles/App.css';
import './styles/mobile.css';
in styles/App.css
I have:
h1 {
font-size: 4.5rem;
font-weight: 700;
margin: 20px 10px 0px 10px;
text-align: center;
color: white;
}
in styles/mobile.css
I have:
@media screen and (max-width: 500px) {
h1 {
font-size: 2rem;
}
}
In my developer tools I am seeing the mobile styles are being overridden:
I thought that if I import the mobile stylesheet under the general stylesheet that the mobile would take precedence, I have used this in other projects and it seemed to work fine. What am I misunderstanding?
CodePudding user response:
Media query styles and usual styles have the same specificity which means h1
inside and outside media queries are similar selectors
In this case, it will check top to bottom in your style declaration (the bottom one will override the top one). You can check the below example
@media screen and (max-width: 2000px) {
h1 {
color: red;
}
}
h1 {
color: blue; /* Get applied */
}
<h1>Testing</h1>
To fix it, you can change your styles' position declaration
h1 {
color: blue;
}
@media screen and (max-width: 2000px) {
h1 {
color: red; /* Get applied */
}
}
<h1>Testing</h1>
If you cannot control your styles' declaration because of your code compilation, you can add another selector to increase the specificity value.
@media screen and (max-width: 2000px) {
body h1 { /* Added `body` here */
color: red; /* Get applied */
}
}
h1 {
color: blue;
}
<h1>Testing</h1>
As for your case
import React from 'react'
import './styles/App.css';
import './styles/mobile.css';
Your style imports may be interfered during compilation, and we won't be sure they will have the same style positions as your imports. I used to face a similar bug, my styles were working well in my localhost, but after uglifying/compressing styles, the style positions got changed without my notice.
I'd suggest that in most cases, we should rely on selectors that will help you to have better code visibility and avoid unexpected styles' applications.
You also can use !important
to have the same effect, but I'd not recommend it. !important
will override all your selector checks, and it will cause more problems when you have many styles applied on the same selector.