2017-11-29 4 views
3

要素がfooter要素でない場合、テキストを赤色にしたいというシンプルなレイアウトです。 pタグ、aタグなどで動作します。CSS3:兄弟要素でnot()セレクタが動作しない

しかし、footerタグで試しても動作しません。

私のコードは以下の通りです:これはあなたのコードは

p { 
 
    color: #000000; 
 
} 
 

 
:not(footer) { 
 
    color: #ff0000; 
 
}
<h1>This is a heading</h1> 
 

 
<footer>This is a footer.</footer> 
 

 
<div>This is some text in a div element.</div> 
 

 
<a href="https://www.w3schools.com" target="_blank">Link to W3Schools!</a>

答えて

2

あなたは:not(footer)が動作するためには、(そうでないfooterが述べられ、ルールに従ってbodyから赤継承されます)bodyである親を選択する必要があります。

よろしくpへのCSS specificity

p { 
 
    color: #000; 
 
} 
 

 
body > *:not(footer) { /* note that having :not(footer) is the same as *:not(footer), the wildcard is not necessary */ 
 
    color: #f00; 
 
}
<h1>This is a heading</h1> 
 

 
<footer>This is a footer.</footer> 
 

 
<div>This is some text in a div element.</div> 
 

 
<p>This is some text in a p element.</p> 
 

 
<a href="https://www.w3schools.com" target="_blank">Link to W3Schools!</a>

+1

これが私の問題を解決しました。ありがとう! – sjw0525

2

です:

footer除いて赤に すべての要素を設定します
:not(footer) { 
    color: #ff0000; 
} 

ルールはbody要素を赤に設定するという問題があります。その後、footerは色を継承します。

あなたのルールは実際に動作します(兄弟は除外されます)が、フッタはそれにもかかわらず継承によって色を取得します。

代わり

または(footerを除く)すべての兄弟を対象に、(footerを除く)すべての子供をターゲットにしています。これは、継承の抜け穴をなくし:

body > :not(footer) { 
 
    color: #ff0000; 
 
}
<h1>This is a heading</h1> 
 

 
<footer>This is a footer.</footer> 
 

 
<div>This is some text in a div element.</div> 
 

 
<a href="https://www.w3schools.com" target="_blank">Link to W3Schools!</a>

2

:not()セレクタは、親要素として、あなたのコードbody tag'll作業にので、ここで動作するためにあなたが入れ子にする親要素を必要とする問題

body > :not(footer){ 
    color: #ff0000; 
} 
+0

フッタの外側とフッタの内側にh3タグがあるとどうなりますか?フッタのh3タグを除くすべてのh3タグに特定のスタイリングが必要なのはどうですか? – sjw0525

+0

フッター内のフッターにクラスを追加し、h3:not(.css){color:red;}と書いてください...理解できるこのペンを見てください(https://codepen.io/satyajit11/pen/XzoWeB) –

+0

Iクラスを追加せずにそれを行うことはできませんか?クラス名の代わりにnot(footer)を使用していますか? – sjw0525

関連する問題