Sunday, 11 May 2014

How first-child, last-child and nth-child Selectors works in CSS

Here is the markup which I'm going to use in this article:
<div class="outercontent">
            <div class="content">
                <p>RowAB</p>
                <p>RowBC</p>
                <p>RowCD</p>
                <p>RowDE</p>
                <a href="#">text in between</a>
                <p>RowEF</p>
            </div>
            <div class="content">
                <p>RowA</p>
                <p>RowB</p>
                <p>RowC</p>
                <p>RowD</p>
                <p>RowE</p>
                <a href="#">link at the end</a>
            </div>
</div>

FIRST-CHILD SELECTOR :- It allows us to target an element that is the first child element within its parent.
these styles will be applied to RowAB and RowA, because they are first child of p parent tag.

LAST-CHILD SELECTOR :- It works absolutely identical as first-child, except that it selects the last element within its parent.
these styles will be applied to RowEF. Why is that? It's because in the second .content div RowE is not the very last child. It's actually a link represented by a tag. Therefore, p:last-child became invalid.

NTH-CHILD SELECTOR :- It allows us to target an element that is the nth child element within its parent
these styles will be applied to RowCD and RowC(because of third element in its scope). We can also pass 2n+0 for example, which styles every element whose index is a multiple of 2.


That’s it!!…..Happy Programming...

No comments:

Post a Comment