Changing CSS for last
  • 2020-01-27 11:37发布

    I am wondering if there is some way to change a CSS attribute for the last li in a list using CSS. I have looked into using :last-child, but this seems really buggy and I can't get it to work for me. I will use JavaScript to do this if necessary, but I want to know if anyone can think up a solution in CSS.

    10条回答
    小情绪 Triste *
    2楼-- · 2020-01-27 12:34

    I've done this with pure CSS (probably because I come from the future - 3 years later than everyone else :P )

    Supposing we have a list:

    <ul id="nav">
      <li><span>Category 1</span></li>
      <li><span>Category 2</span></li>
      <li><span>Category 3</span></li>
    </ul>
    

    Then we can easily make the text of the last item red with:

    ul#nav li:last-child span {
       color: Red;
    }
    
    查看更多
    beautiful°
    3楼-- · 2020-01-27 12:34

    You could use jQuery and do it as such way

    $("li:last-child").addClass("someClass");
    
    查看更多
    萌系小妹纸
    4楼-- · 2020-01-27 12:38

    :last-child is really the only way to do it without modifying the HTML - but assuming you can do that, the main option is just to give it a class="last-item", then do:

    li.last-item { /* ... */ }
    

    Obviously, you can automate this in the dynamic page generation language of your choice. Also, there is a lastChild JavaScript property in the W3C DOM.

    Here's an example of doing what you want in Prototype:

    $$("ul").each(function(x) { $(x.lastChild).addClassName("last-item"); });
    

    Or even more simply:

    $$("ul li:last-child").each(function(x) { x.addClassName("last-item"); });
    

    In jQuery, you can write it even more compactly:

    $("ul li:last-child").addClass("last-item");
    

    Also note that this should work without using the actual last-child CSS selector - rather, a JavaScript implementation of it is used - so it should be less buggy and more reliable across browsers.

    查看更多
    够拽才男人
    5楼-- · 2020-01-27 12:38

    I usually combine CSS and JavaScript approaches, so that it works without JavaScript in all browsers but IE6/7, and in IE6/7 with JavaScript on (but not off), since they does not support the :last-child pseudo-class.

    $("li:last-child").addClass("last-child");
    
    li:last-child,li.last-child{ /* ... */ }
    
    查看更多
    登录 后发表回答