在我的 App.js 中,我有以下匯入:
import React from 'react'
import './styles/App.css';
import './styles/mobile.css';
在styles/App.css我有:
h1 {
font-size: 4.5rem;
font-weight: 700;
margin: 20px 10px 0px 10px;
text-align: center;
color: white;
}
在styles/mobile.css我有:
@media screen and (max-width: 500px) {
h1 {
font-size: 2rem;
}
}
在我的開發人員工具中,我看到移動樣式被覆寫:
我認為如果我在移動設備優先的通用樣式表下匯入移動樣式表,我已經在其他專案中使用過它,它似乎作業正常。我有什么誤解?
uj5u.com熱心網友回復:
媒體查詢樣式和常用樣式具有相同的特性,這意味著h1內部和外部媒體查詢是相似的選擇器
在這種情況下,它將在您的樣式宣告中從上到下檢查(底部的將覆寫頂部的)。您可以查看以下示例
@media screen and (max-width: 2000px) {
h1 {
color: red;
}
}
h1 {
color: blue; /* Get applied */
}
<h1>Testing</h1>
要修復它,您可以更改樣式的位置宣告
h1 {
color: blue;
}
@media screen and (max-width: 2000px) {
h1 {
color: red; /* Get applied */
}
}
<h1>Testing</h1>
如果由于代碼編譯而無法控制樣式的宣告,則可以添加另一個選擇器以增加特異性值。
@media screen and (max-width: 2000px) {
body h1 { /* Added `body` here */
color: red; /* Get applied */
}
}
h1 {
color: blue;
}
<h1>Testing</h1>
至于你的情況
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.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/457649.html
