5

bien dicen que no hay pregunta tonta así que aquí les hago la mía.

Tengo una lista de div's dentro de un div

<div class="container">
 <div>1</div>
 <div>2</div>
 <div>3</div>
 <div>4</div>
 <div>5</div>
 <div>6</div>
</div>

Quiero seleccionar el div con el número 1 con Css. Ya intenté el nth-child(1) y first-child.

3 respuestas 3

8

nth-child(1) y first-child deberían funcionarte, probablemente hayas colocado algo mal en tu css. Seleccionar el primer div dentro del div con la clase container se puede hacer de diferentes manera:

/*seleccionarán el primer hijo div dentro de container y dentro de los hijos de container*/
.container div:nth-child(1){ }
.container div:first-child{ }
.container div:first-of-type{ }/*ignorará los elementos anteriores que no sean divs*/

/*seleccionarán el primer hijo div directo dentro de container*/
.container > div:nth-child(1){ }
.container > div:first-child{ }
.container > div:first-of-type{ }/*ignorará los elementos anteriores que no sean divs*/
6

Puedes utilizar la pseudo clase :first-child sobre el elemento que tiene varios hermanos;

.container > div:first-child {
    color: red;
}
<div class="container">
  <div>DIV 1</div>
  <div>DIV 2</div>
  <div>DIV 3</div>
  <div>DIV 4</div>
</div>

6

Prueba first-of-type:

div.container > div:first-of-type {
  background: red;
}
<div class="container">
 <div>1</div>
 <div>2</div>
 <div>3</div>
</div>

Edit: Como han mencionado @asantana o y @Carlos Ormeño, tanto first-child como nth-child deberían funcionar:

div.container > div:first-child {
  background: red;
}
<div class="container">
 <div>1</div>
 <div>2</div>
 <div>3</div>
</div>

div.container > div:nth-child(1) {
  background: red;
}
<div class="container">
 <div>1</div>
 <div>2</div>
 <div>3</div>
</div>

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.