简体   繁体   中英

Use last-child on angular selector

How do I get the last-child CSS selector to work on an angular component selector? I want to add styles to the last component item with a particular class.

My HTML:

<component-name class="abc"></component-name>
<component-name class="abc"></component-name>
<component-name class="abc"></component-name>
<component-name class="efg"></component-name>
<component-name class="efg"></component-name>

In the case above, I would like to style the last .abc item. So my CSS:

component-name.abc:last-child {
 // some styles
}

This doesn't work. Neither does this:

component-name.abc:last-of-type {
    // some styles
}

How do I select the last-child in this case?

Is the css code you posted within the component-name.css -file? If that's the case move it to the parent component style sheet or style.css .

You can use jQuery last()

Stack Snippet

 $('component-name.abc').last().css( "background-color", "red" ) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <component-name class="abc">abc</component-name> <component-name class="abc">abc</component-name> <component-name class="abc">abc</component-name> <component-name class="efg">efg</component-name> <component-name class="efg">efg</component-name> 

Reference Link:

You could try the nth-of-type selector.

I made a fiddle: https://jsfiddle.net/34vwp9xd/

.abc:nth-of-type(3) {
  background:red;
}

But it's less than ideal because you have to know the index of the class you want to style, I think your going to need to use JS to solve this by adding a last class to the last element of class abc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM