How to select the first child from all similar class in css

Viewed 237

How to select the first child from all similar class in css

HTML

<div class="parent">
    <div class="no-a-child"><span>1</span></div>
    <div class="child"><span>2</span></div>
    <div class="child"><span>3</span></div>
    <div class="child"><span>4</span></div>
</div>

CSS

.parent .child:nth-child(1) span {
  color:red;
}

.parent .child:nth-child(1) span {
  color: red;
}
<div class="parent">
  <div class="no-a-child"><span>1</span></div>
  <div class="child"><span>2</span></div>
  <div class="child"><span>3</span></div>
  <div class="child"><span>4</span></div>
</div>

Here I want a red color:

<div class="child"><span>2</span></div>
4 Answers

One approach to achieve this effect requires two stages:

  1. Declare a style for a given class
  2. Undo that style for all elements of that class which follow the first element of that class

Working Example:

/* Declare a style for a given class */

.child {
  color: rgb(255, 0, 0);
}

/* Undo that style for all elements of that class which follow the first */

.child ~ .child {
  color: inherit;
}
<div class="parent">
    <div class="no-a-child"><span>1</span></div>
    <div class="child"><span>2</span></div>
    <div class="child"><span>3</span></div>
    <div class="child"><span>4</span></div>
</div>

I'm not sure if I understood well, but i guess you want just the first class child to be in red, and not the class no-a-child...if so, just use this

.parent :nth-of-type(2) span{
  color: red;
}
  <div class="parent">
      <div class="no-a-child"><span>1</span></div>
      <div class="child"><span>2</span></div>
      <div class="child"><span>3</span></div>
      <div class="child"><span>4</span></div>
  </div>

If you want the first div that has class child you could try something like:

div.child:nth-of-type(1).

Use a adjacent sibling combinator https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_combinator to target the next element after the no-a-child class element as that seems to be what you really desire.

I added another example (cyan color) that illustrates that option

.parent > .no-a-child+.child>span {
  color: #FF0000;
}

.parent-second> div:first-of-type + div>span {
  color: #00FFFF;
}
<div class="parent">
  <div class="no-a-child"><span>1</span></div>
  <div class="child"><span>2</span></div>
  <div class="child"><span>3</span></div>
  <div class="child"><span>4</span></div>
</div>

<div class="parent-second">
  <div class="no-a-child"><span>1</span></div>
  <div class="child"><span>2</span></div>
  <div class="child"><span>3</span></div>
  <div class="child"><span>4</span></div>
</div>

Related