樣式的繼承
定義:父元素設置了某屬性,子元素也會有該屬性
下面是會被繼承的CSS樣式屬性:
azimuth, border-collapse, border-spacing,
caption-side, color, cursor, direction, elevation,
empty-cells, font-family, font-size, font-style,
font-variant, font-weight, font, letter-spacing,
line-height, list-style-image, list-style-position,
list-style-type, list-style, orphans, pitch-range,
pitch, quotes, richness, speak-header, speaknumeral,
speak-punctuation, speak, speechrate,
stress, text-align, text-indent, texttransform,
visibility, voice-family, volume, whitespace,
widows, word-spacing
文本相關屬性:
font-family, font-size, font-style,
font-variant, font-weight, font, letter-spacing,
line-height, text-align, text-indent, texttransform,word-spacing
列表相關屬性:
list-style-image, list-style-position,
list-style-type, list-style
樣式的覆蓋
規則:
-
根據引入方式確定優先級
優先級由高到低依次為:“內聯屬性”——>“寫在 style標簽里”——>“外部鏈接” -
后寫的覆蓋先寫的(同一級別)
即就是在文件上代碼行號更靠下的優先級更高 -
加有“!important”的樣式,優先級最高
即無論哪一種情況,只要在樣式上加了important,那么該樣式的優先級最高。加了important的代碼如下:
p {
color: white !important;
}
-
選擇器優先級
在選擇器不同的情況下,給每種選擇器制定一個權值,計算命中一個元素的所有選擇器的總權值,值高者獲勝
- 元素選擇器: 1
- 類選擇起器: 10
- ID選擇器: 100
- 內聯選擇器: 1000
樣式繼承與覆蓋示例
- 樣式繼承不是一個默認行為,實際上而是看某一個屬性的默認值是否是inherit。 所謂的瀏覽器默認樣式。a標簽的color瀏覽器默認樣式不是inherit。代碼如下所示:
.abstract{
color:grey;
}
.abstract a{
color:inherit;
text-decoration:none;
border:thin black solid;
}
.different {
color: red ;
}
.different a{
text-decoration: none ;
border:thin black solid;
}
執行效果如下圖:
demo1.png
詳細代碼[點這里](https://github.com/tw-lab-roadmap-1/YangHuili-task2-homework2/tree/master/demo1)
- 前面講到外部文件引用css的優先級比style標簽里的低。 但是id選擇器的優先級是比元素選擇器要高的。所以當元素選擇器和id選擇器都命中同樣的元素的時候, id選擇器的樣式會覆蓋元素選擇器的樣式。
代碼如下:
h1{
color:red;
}
#change{
color:blue;
}
執行效果如下:
demo2.png
詳細代碼點這里
- 我們知道內聯樣式的優先級是最高的,那么當元素已經被內聯樣式設置的時候。我們通過 !important 來覆蓋。代碼如下:
<body>
<h1 id="change" style="color: grey">
HelloWord,你看到的是已經經歷過三次變換的文字。
</h1>
</body>
h1{
color: red;
}
#change{
color:black !important
}
執行效果如下:
demo3.png
詳細代碼點這里
- 若給一種元素設置了普適的效果,如何通過更精確的選擇器將其覆蓋掉,代碼如下:
a{
color:black;
}
a.hehe{
color:white;
background:grey;
}
詳細代碼點這里
- 當一個元素有兩個class的時候,到底哪個class會影響 元素呢, 代碼如下:
a.hehe1{
color:black;
}
a.hehe2{
color:white;
background:grey;
}
文件上代碼行號更靠下的優先級更高,即后寫的覆蓋先寫的。
詳細代碼點這里
- 讓span繼承abstract的border屬性。代碼如下:
.abstract{
color:white;
background:grey;
border:medium black solid;
}
span{
border:inherit
}
如上所示,將span 的 border 屬性設為“inherit”,span 就會繼承父元素的樣式。
詳細代碼點這里