簡體   English   中英

為什么color屬性沒有改變?

[英]Why the color property isn't changing?

媒體查詢將更改所有內容,但不會更改color屬性。 我想知道為什么? 僅當我未定義color屬性並將其保留為默認值時,此方法才有效。 為什么媒體查詢無法更改顏色?

https://jsfiddle.net/6spv3mrf/

<style>
@media only screen and (max-width: 900px) {
  h1 {
    color: red;
    /*doesn't work*/
    background-color: yellow;
    /*works*/
  }

}

body {
  background-color: yellowgreen;
  font-family: sans-serif;
}

#box {
  width: 50%;
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  z-index: 1;
}

#text {
  min-height: 80%;
  margin: 25% 10%;
  padding: 10px;
}

h1 {
  font-weight: bold;
  font-size: 2em;
  margin: 0;
  color: #000;
  text-align: left;
}

</style>

您需要 h1 css 之后移動@media css。 現在,您基本上已經用普通的CSS覆蓋了@media屬性。 如果添加例如body的內部@media屬性那么你一般body CSS也應該在前面定義的@media屬性。

您可以在官方文檔中找到更多信息:

查找目標媒體類型適用於相關元素和屬性的所有聲明。 如果關聯的選擇器與所討論的元素匹配,並且目標媒體與所有包含聲明的@media規則以及到達樣式表的路徑上的所有鏈接上的媒體列表相匹配,則聲明適用。

您可以在鏈接上找到完整的文檔。

h1 {
  font-weight: bold;
  font-size: 2em;
  margin: 0;
  color: #000;
  text-align: left;
}

@media only screen and (max-width: 900px) {
  h1 {
    color: red;
    /*doesn't work*/
    background-color: yellow;
    /*works*/
  }
}

body {
  background-color: yellowgreen;
  font-family: sans-serif;
}

#box {
  width: 50%;
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  z-index: 1;
}

#text {
  min-height: 80%;
  margin: 25% 10%;
  padding: 10px;
}

將媒體查詢移至CSS的末尾,以獲取有關其工作原理的更多信息

body {
  background-color: yellowgreen;
  font-family: sans-serif;
}

#box {
  width: 50%;
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  z-index: 1;
}

#text {
  min-height: 80%;
  margin: 25% 10%;
  padding: 10px;
}

h1 {
  font-weight: bold;
  font-size: 2em;
  margin: 0;
  color: #000;
  text-align: left;
}

@media only screen and (max-width: 900px) {
  h1 {
    color: red;
    /*doesn't work*/
    background-color: yellow;
    /*works*/
  }
}

正如我們已經在評論中所寫:媒體查詢必須遵循通用規則之后,因為否則它會被通用規則中的屬性覆蓋(適用於所有內容,因此是有序的):

這是小提琴中的(已編輯)代碼,順便說一句,您也可以在此處將代碼片段放入其中:

 body { background-color: yellowgreen; font-family: sans-serif; } #box { width: 50%; position: fixed; top: 0; right: 0; bottom: 0; background-color: #fff; z-index: 1; } #text { min-height: 80%; margin: 25% 10%; padding: 10px; } h1 { font-weight: bold; font-size: 2em; margin: 0; color: #000; text-align: left; } @media only screen and (max-width: 900px) { h1 { color: red; /*doesn't work*/ background-color: yellow; /*works*/ } } 
 <div id="box"> <div id="text"> <h1> Random<br> Text </h1> </div> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM