Consider this snippet:
.test input.one ~ div:nth-of-type(2) {
background-color: red;
}
.test input.two ~ div:nth-of-type(2) {
background-color: blue;
}
<form class="test">
<input class="one" />
<div></div>
<input class="two" />
<div style="height: 50px;"></div>
<div style="height: 50px;"></div>
</form>
What I would expect to happen is that the first <div style="height: 50px;"></div>
would be red, and the second one would be blue. Instead, the nth-of-type(2)
selector is selecting the first <div style="height: 50px;"></div>
both times.
I thought that .test input.two ~ div:nth-of-type(2)
would start at <input class="two" />
, and count downwards 2 <div>
tags, and land on the second one?
What's happening here?
nth-of-type()
"matches elements of a given type, based on their position among a group of siblings". Your code is selecting the <div>
that is preceded by input.two
and is also the second <div>
sibling in the parent element.
In your case, you might consider using the adjacent sibling combinator. Below, I'm selecting the <div>
that immediately follows .one
(red) and the <div>
that immediately follows the <div>
that immediately follows .two
(blue).
.one + div {
background-color: red;
}
.two + div + div {
background-color: blue;
}
<form class="test">
<input class="one" value="one">
<div>A</div>
<input class="two" value="two">
<div>B</div>
<div>C</div>
</form>
Just for fun, here's an example to help visualize nth-of-type
by grouping elements in separate parent containers.
.one ~ div:nth-of-type(1) {
background-color: red;
}
.two ~ div:nth-of-type(2) {
background-color: blue;
}
<form class="test">
<div>
<input class="one" value="one">
<div>A</div>
</div>
<div>
<input class="two" value="two">
<div>B</div>
<div>C</div>
</div>
</form>
Este artículo se recopila de Internet, indique la fuente cuando se vuelva a imprimir.
En caso de infracción, por favor [email protected] Eliminar
Déjame decir algunas palabras