Wednesday, April 3, 2019

html - select an element "inside" the :first-child pseudo selector using CSS



Good day all.



I have a problem, a structure like this:






















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


Answer



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


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...