Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

89
Views
How to target first and last elements of a class

I have this simple markup of a table:

<div class="table">
  <div class="table__headers"></div>
  <div class="table__row"></div>
  <div class="table__row"></div>
</div>

And I've styled it using this CSS:

<style lang="scss" scoped>
.grid {
    display: grid;
    grid-gap: 0.5rem;
}

.table {
    &__headers,
    &__row {
        @extend .grid;
        padding: 0.5rem 0.75rem;

        :first-child {
            text-align: start;
        }

        :last-child {
            text-align: end;
        }

        p {
            font-size: 0.8rem;
            font-weight: bold;
            text-align: center;
            margin: 0;
        }
    }

    &__row {
        background: #f8f8fa;
    }
}
</style>

My only issue is that I'm not able to specifically target the first and last table__row elements so I can style them differently.

The following does not work:

&__row:first-of-type {
  border: solid 1px red;
}

&__row:last-of-type {
  border: solid 1px blue;
}

last-of-type works but not first of type. Any help would be appreciated!

Thank you,

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Here's a JavaScript solution:

let rows = document.querySelectorAll(".table__row"); // Get all rows into an "array-like" object
rows[0].classList.add("firstRow");                   // Get and style first row
rows[rows.length-1].classList.add("lastRow");        // Get and style last row
.firstRow { background-color:red; }
.lastRow { background-color:green; }
<div class="table">
  <div class="table__headers"></div>
  <div class="table__row">blah</div>
  <div class="table__row">blah</div>
  <div class="table__row">blah</div>
  <div class="table__row">blah</div>
  <div class="table__row">blah</div>
  <div class="table__row">blah</div>
</div>

about 4 years ago · Juan Pablo Isaza Report

0

The reason that :first-of-type is not working is because it's the functional equivalent of :nth-child(1), when what you need is :nth-child(2) due to the preceding <div> element.

These selectors are intended to work using elements (TagName) and not classes.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!