Search code examples
csscss-selectorsclearfix

Clearfix breaks the :last-child


It's weird but when I use the :last-child to my elements, and then put a clearfix div in the end, it breaks the last-child? Any ideas anyone?

HTML:

<div>
    <a href="#">first child</a>
    <a href="#">second child</a>
    <a href="#">third child</a>
    <a href="#">last/forth child</a>

    <div class="clearfix"></div>
     This is after the clearfix
</div>

CSS:

a{
        display: block;
        margin: 5px;
        color: red;
        width: 80px;
        float: left;
    }

    a:last-child{
        color: blue;
    }

    .clearfix:before, .clearfix:after {
        content: " ";
        display: table;
    }
    .clearfix:after {
    clear: both;
    }

JSFIDDLE


Solution

  • Yes because that is what last-child selector does. Selects the element that is the last child of its parent.

    If you add and another div after your last a this will div be the last child of its parent.

    a:last-child{
        color: blue;
    }
    

    This selects a elements that are last child of its parent.

    In this format:

    <div>
        <a href="#">first child</a>
        <a href="#">second child</a>
        <a href="#">third child</a>
        <a href="#">last/forth child</a>
    
        <div class="clearfix"></div>
         This is after the clearfix
    </div>
    

    will not select last a because it is not the last child of its parent div

    In the other hand this markup:

    <div>
        <a href="#">first child</a>
        <a href="#">second child</a>
        <a href="#">third child</a>
        <div class="clearfix"></div>
        <a href="#">last/forth child</a>
    
    
         This is after the clearfix
    </div>
    

    will select the last a element.