Search code examples
csscss-selectorspseudo-class

:first-of-type acting as if it doesn't exist?


I am using :first-of-type pseudo class to remove a margin although its behaving as if im not using first-of-type at all and removes the margin on all the elements.

Here is the code:

HTML

<ul id="share" class="hidden-xs">
        <li><a href="#" class="twitter-share socialicon" title="Share on Twitter"><em class="fa fa-twitter" aria-hidden="true"></em><div class="sr-only">Share on Twitter</div></a></li>
  <li><a href="#" class="instagram-share socialicon" title="Share on Instagram"><em class="fa fa-instagram" aria-hidden="true"></em><div class="sr-only">Share on Instagram</div></a></li>
        <li><a href="#" class="envelope-share socialicon" title="Share via Email"><em class="fa fa-envelope" aria-hidden="true"></em><div class="sr-only">Share via Email</div></a></li>
</ul>

CSS

.socialicon {
    margin-left: 80px;
    font-size: 12px;
    vertical-align: middle;
}

.socialicon:first-of-type {
    margin-left: 0px;
}


ul#share{
    margin: 0px;
    padding: 0px;
    list-style: none;
    display: inline;
    line-height: 19px;
    margin-left: 15px;
}
ul#share li{
    display: inline-block;
}
ul#share li span {
    color: white;
    font-weight: 600;
    text-transform: uppercase;
}

JSFIDDLE


Solution

  • :first-of-type is not exactly intuitive in what it does - it does not take the entire document into account, but takes the parent element as reference point. In that sense, each of your anchor elements is the "first element of its type" within the enclosing li element and that's why the selector is applied on each of those elements. What you instead have to do is move the :first-of-type one level down to the li element. Since they are all on the same level, only the first li is affected. (However, this would affect the first li in another list on the same page as well).

    li:first-of-type .socialicon{
        margin-left: 0px;
    }
    

    your modified fiddle