2017-11-23 6 views
2

first-of-typeと:last-of-typeセレクタは、以下のスニペットのように動作する理由を説明できますか?データ型のlast-of-typeセレクタの動作

https://codepen.io/anon/pen/jaxQNJ

HTML

<div class="container"> 
    <h2 data-type data-type-a>A (should be black/is black)</h2> 
    <h2 data-type data-type-a>A (should be red/is black)</h2> 
    <h2 data-type data-type-b>B (should be green/is black)</h2> 
    <h2 data-type data-type-b>B (should be blue/is blue)</h2> 
</div> 

CSS

div{ 
    color:black; 
    font-weight:bold; 
} 

.container h2[data-type]:last-of-type{ 
    color:blue; 
} 

.container h2[data-type-a]:last-of-type{ 
    color:red; 
} 

.container h2[data-type-b]:first-of-type{ 
    color:green; 
} 

答えて

0

:last-of-type:first-of-typeは期待通りに働いている:

:最後の型CSSの擬似CLA ssは、兄弟要素のグループの中でタイプの最後の要素を表します。

問題は、この特定のセレクタは、あなたの属性セレクタを無視して、タイプh2最後の要素をターゲットにしていることです。 タイプh2であり、data-typeまたはdata-type-aではないためです。

私はそれはそれが意味何だ、classを使用するためにあなたをお勧めします:

div { 
 
    color: black; 
 
    font-weight: bold; 
 
} 
 

 
.data-type-b { 
 
    color: green; 
 
} 
 

 
.data-type-a { 
 
    color: red; 
 
} 
 

 
.data-type:first-child { 
 
    color: inherit; 
 
} 
 

 
.data-type:last-child { 
 
    color: blue; 
 
}
<div class="container"> 
 
    <h2 class="data-type data-type-a">A (should be black/is black)</h2> 
 
    <h2 class="data-type data-type-a">A (should be red/is red)</h2> 
 
    <h2 class="data-type data-type-b">B (should be green/is green)</h2> 
 
    <h2 class="data-type data-type-b">B (should be blue/is blue)</h2> 
 
</div>

関連する問題