Style first and last element for each

275 Views Asked by At

I'm trying to style the first and last list item within the "wrapper" class by applying the "red" class. I have multiple sections on the page with the "wrapper" class.

<div class="wrapper">
  <div class="section">
    <ul class="parent">
      <li class="child">List Item</li>
      <li class="child">List Item</li>
      <li class="child">List Item</li>
      <li class="child">List Item</li>
      <li class="child">List Item</li>
      <li class="child">List Item</li>
    </ul>
  </div>
</div>
<div class="wrapper">
  <div class="section">
    <ul class="parent">
      <li class="child">List Item</li>
      <li class="child">List Item</li>
      <li class="child">List Item</li>
      <li class="child">List Item</li>
      <li class="child">List Item</li>
      <li class="child">List Item</li>
    </ul>
  </div>
</div>

https://jsfiddle.net/n2bg3zu4/

3

There are 3 best solutions below

0
Jose Mato On

You can use css3 to do that:

.parent li:first-child, .parent li:last-child {
    background-color: red;
}

First and last li (list item) will be read in each .parent element

0
guest271314 On

trying to style the first and last list item within the "wrapper" class

Try utilizing :nth-of-type() , :nth-last-of-type()

.wrapper li:nth-of-type(1),
.wrapper li:nth-last-of-type(1) {
  background-color: red;
}
<div class="wrapper">
  <div class="section">
    <ul class="parent">
      <li class="child">List Item</li>
      <li class="child">List Item</li>
      <li class="child">List Item</li>
      <li class="child">List Item</li>
      <li class="child">List Item</li>
      <li class="child">List Item</li>
    </ul>
  </div>
</div>
<div class="wrapper">
  <div class="section">
    <ul class="parent">
      <li class="child">List Item</li>
      <li class="child">List Item</li>
      <li class="child">List Item</li>
      <li class="child">List Item</li>
      <li class="child">List Item</li>
      <li class="child">List Item</li>
    </ul>
  </div>
</div>

jsfiddle https://jsfiddle.net/n2bg3zu4/4/

0
Suman Barick On

Using jQuery you can write,

$('.wrapper .parent li:first-child, .wrapper .parent li:last-child').addClass('red')