0

Good day all.

I have a problem, a structure like this:

<ul>
    <li>
        <span><span>
    </li>
    <li class="selected">
        <span><span>
    </li>
    <li class="selected">
        <span><span>
    </li>
    <li class="selected">
        <span><span>
    </li>
    <li>
        <span><span>
    </li>
</ul>

I would like to select the first and last that have selected on the parent... the pseudo code should be like this:

li.selected span { background: #FF4D6E; color: white; }
li.selected:first-child span{border-radius:30px;}
li.selected:last-child span{border-radius:30px;}

the problem is that the span is inside the collection of .selected so I would like to have the first .selected, and its span

Matteo Bononi 'peorthyr'
  • 2,170
  • 8
  • 46
  • 95

4 Answers4

3

That is not possible because .selected class element is not the first of its parent. But you can do a workaround here by using sibling selectors as shown below:

/* first child */
li.selected span{
    border-radius: 30px;
}

/* middle children */
li.selected + li.selected span{
     border-radius: 0px;
}

/* last child */
li.selected ~ li.selected ~ li.selected span {
     border-radius: 30px;
}

Above code is assuming you have only three .selected elements. If you have more and you know the count then change the last child code in the above with respect to the count. For example, if you have four .selected elements.

li.selected ~ li.selected ~ li.selected ~ li.selected span {     
     border-radius: 30px;
}

Example Fiddle

Mr_Green
  • 40,727
  • 45
  • 159
  • 271
0

If you are using jQuery then do this:

$("li.selected span").css("background" : "#FF4D6E", "color" : "#fff");

$("li.selected:first-child span").css("border-radius" : "30px");

$("li.selected:last-child span").css("border-radius" : "30px");
Edward Manda
  • 559
  • 3
  • 7
0

To do this, I recommend taking a few hours to learn jquery. Here is a link to a good jquery tutorial. You can finish this tutorial in about three hours.

Jquery allows you to dynamically select any element that you want and modify it in pretty much any way you can imagine.

This is the code I would use to modify the CSS of the first and last span elements with .selected parents:

var $childOfSelected = $('.selected').children('span')

$childOfSelected.last().css({'border-radius':'30px'});
$childOfSelected.first().css({'border-radius':'30px'});
Goodword
  • 1,565
  • 19
  • 27
0

For the first child you can use this

li.selected span {
  background: #FF4D6E;
  color: white;
}
.selected:first-child,
:not(.selected) + .selected span {
  border-radius: 30px;
}
<ul>
    <li>
        <span>not</span>
    </li>
    <li class="selected">
        <span>selected</span>
    </li>
    <li class="selected">
        <span>selected</span>
    </li>
    <li class="selected">
        <span>selected</span>
    </li>
    <li>
        <span>not</span>
    </li>
</ul>
Bojan Petkovski
  • 6,835
  • 1
  • 25
  • 34