CSS general sibling and nth-of-type selector - odd behavior?

Timothy Fisher

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?

showdev

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

Editado en
0

Déjame decir algunas palabras

0Comentarios
Iniciar sesiónRevisión de participación posterior

Artículos relacionados

nth child selector css

CSS - selector nth-child

CSS Nth of Type no orientado

Как очистить большой массив повторяющихся селекторов CSS Nth-Of-Type?

Tratando de entender el selector css de tipo nth-of-type

Tratando de entender el selector css de tipo nth-of-type

Problems using jQuery selector "nth-of-type"

CSS Trick: nth-of-type()

CSS nth-of-type на том же уровне DOM

Problemas al usar el selector de jQuery "nth-of-type"

nth-child (number) Selector para CSS que no se aplica

¿Por qué el selector nth-child no funciona en css?

nth-child (number) Selector para CSS que no se aplica

¿Puedo combinar: nth-child () o: nth-of-type () con un selector arbitrario?

Cómo comprobar si el navegador admite el selector general de hermanos CSS ~

CSS nth-of-type en el mismo nivel DOM

¿Cómo funciona el selector CSS3: nth-child ()?

Selector de CSS para el primer elemento de nth-flex-row

css nth-child first n selector ne fonctionne pas avec l'état de survol

¿Por qué el equivalente nth-child funciona para el selector css pero no para xpath?

El selector de CSS con nth-child funciona pero no last-child

Cuadrícula de mampostería con CSS usando el pseudo-selector: nth-child?

El selector CSS no sigue la lógica ': nth-child' para bs4

¿Cómo seleccionar un número personalizado de filas usando el selector CSS "nth-child"?

Select specific divs with an nth selector?

odd behavior of do() function in dplyr

JSONIFY Filter Odd Behavior in Jekyll

SwiftUI odd animation behavior with systemImage

Ожидание загрузки идентифицирующего элемента с помощью CSS Selector