amars
amars

Reputation: 407

Selecting first child from all elements and nested elements

I need to only select the first and third/last elements.

It was working fine until I decided to make them links. In my actual source the divs are imgs

body {
  background-color: black;
  color: white;
}

.this:first-child {
  color: red;
}

.this:last-child {
  color: aqua;
}
<div class="main">
  <a href="">
    <div class="this">
      FIRST
    </div>
  </a>
  <a href="">
    <div class="this">
      SECOND
    </div>
  </a>
  <a href="">
    <div class="this">
      THIRD
    </div>
  </a>
</div>

Upvotes: 0

Views: 80

Answers (1)

Ori Drori
Ori Drori

Reputation: 193258

Your .this elements are wrapped with another element (a), and they are the only children. This means that they are both first and last child, so the last rule takes over. Move the :first-child and :last-child pseudo-selectors to the a elements:

body {
  background-color: black;
  color: white;
}

a:first-child .this {
  color: red;
}

a:last-child .this {
  color: aqua;
}
<div class="main">
  <a href="">
    <div class="this">
      FIRST
    </div>
  </a>
  <a href="">
    <div class="this">
      SECOND
    </div>
  </a>
  <a href="">
    <div class="this">
      THIRD
    </div>
  </a>
</div>

Upvotes: 2

Related Questions