CSS Target Specific Child

Glenn Glenn's Blog 0 Comments

First lets look at how jQuery Does it 🙂

With jQuery it’s easy to target a specific first child with jQuery First:-

<script type="text/javascript">
$("p span").first().addClass('highlight');

Or if it’s not the first then the <strong>:nth-child() Selector</strong> like so:-

<script type="text/javascript">
$("ul li:nth-child(2)").append("<span> - 2nd!</span>");

This selects the second ‘li’ in the ‘ul’ and appends a span

Or a combination of selectors such as ‘first’ and ‘:nth-child’

<script type="text/javascript">
$(".location table tbody tr").find('td:first, td:nth-child(2)').addClass('your-class');

This finds the second ‘td’ in each ‘tr’ and adds a class

But did you know this can also be easily done with CSS?

CSS First, Nth, Last Child

Simply apply the following CSS to your Div:-

.yourclass .pp2:first-child {}
.yourclass .pp2:nth-child(2) {}
.yourclass .pp2:last-child {}

Just add the CSS to be applied between the {} so:-

.soapboxes .pp2:nth-child(2) {margin-right: 1.78%;}

This adds a margin of 10% to the second div with class .pp2 under parent .soapboxes. And for those of you that are interested this is also the setting you can use to get 3 Soapboxes in the WordPress Pagelines Framework rather than 2 (which is the de-facto setting). Set the width of each pp2 div to 29.99% for it to work cross device.

This will work in all modern browsers.

About the Author
CSS Target Specific Child CSS Target Specific Child 0da77002febbfe28d15144a57bbcc2c9 s 180 d mm r g


A highly experienced WordPress Web Developer, Front-end and Back-end Developer & New Media Specialist with extensive knowledge of a wide spectrum of technologies in the Development and Creative Industries built up over a number of years.