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');
</script>>

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

&lt;script type=&quot;text/javascript&quot;&gt;
$(&quot;ul li:nth-child(2)&quot;).append(&quot;&lt;span&gt; - 2nd!&lt;/span&gt;&quot;);
&lt;/script&gt;

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

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

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

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:-

[css]
.yourclass .pp2:first-child {}
.yourclass .pp2:nth-child(2) {}
.yourclass .pp2:last-child {}
[/css]

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

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

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

Glenn

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.

Leave a Reply

Your email address will not be published. Required fields are marked *