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条回答
    相关推荐>>
    2楼-- · 2020-01-27 12:19

    :last-child is CSS3 and has no IE support while :first-child is CSS2, I believe the following is the safe way to implement it using jquery

    $('li').last().addClass('someClass');
    
    查看更多
    做个烂人
    3楼-- · 2020-01-27 12:25

    One alternative for IE7+ and other browsers may be to use :first-child instead, and invert your styles.

    For example, if you're setting the margin on each li:

    ul li {
      margin-bottom: 1em;
    }
    ul li:last-child {
      margin-bottom: 0;
    }
    

    You could replace it with this:

    ul li {
      margin-top: 1em;
    }
    ul li:first-child {
      margin-top: 0;
    }
    

    This will work well for some other cases like borders.

    According to sitepoint, :first-child buggy, but only to the extent that it will select some root elements (the doctype or html), and may not change styles if other elements are inserted.

    查看更多
    我命由我不由天
    4楼-- · 2020-01-27 12:26

    2015 Answer: CSS last-of-type allows you to style the last item.

    ul li:last-of-type { color: red; }
    
    查看更多
    相关推荐>>
    5楼-- · 2020-01-27 12:30

    If you know there are three li's in the list you're looking at, for example, you could do this:

    li + li + li { /* Selects third to last li */
    }
    

    In IE6 you can use expressions:

    li {
        color: expression(this.previousSibling ? 'red' : 'green'); /* 'green' if last child */
    }
    

    I would recommend using a specialized class or Javascript (not IE6 expressions), though, until the :last-child selector gets better support.

    查看更多
    啃猪蹄的小仙女
    6楼-- · 2020-01-27 12:32

    I usually do this by creating a htc file (ex. last-child.htc):

    <attach event="ondocumentready" handler="initializeBehaviours" />
    <script type="text/javascript">
    function initializeBehaviours() {
      this.lastChild.className += ' last-child';
    }
    </script>
    

    And call it from my IE conditional css file with:

    ul { behavior: url("/javascripts/htc/last-child.htc"); }

    Whereas in my main css file I got:

    ul li:last-child,
    ul li.last-child {
      /* some code */
    }
    

    Another solution (albeit slower) that uses your existent css markup without defining any .last-child class would be Dean Edwards ie7.js library.

    查看更多
    迷人小祖宗
    7楼-- · 2020-01-27 12:33

    $('li').last().addClass('someClass');

    if you have multiple

  • group it will only select the last li.

  • 查看更多
    登录 后发表回答