Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

97
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda