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,
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>
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.