Apply CSS to the specific <a> in the div

So, I have the following div in HTML. Now I was wondering if there is a way to apply CSS only to the first 2 <a> and other Css on the third <a>

 <div id="contain"> <div> <a href="#" id="A">A</a> <a href="#" id="B">B</a> <a href="#" id="C">C</a> </div> </div> 

CSS

 #contain a { margin: 10px 20px 10px 20px; text-decoration: none; display: inline-block; } 

I want to apply the above Css only to the first 2 <a> in the Div.

Thanks for the help.:)

+6
source share
6 answers

You should use nth-child() to target the first two elements ...

 #contain a:nth-child(-n+2){ margin: 10px 20px 10px 20px; text-decoration: none; display: inline-block; } 

Demo

Update: using :nth-of-type()

  #contain a:nth-of-type(-n+2){ margin: 10px 20px 10px 20px; text-decoration: none; display: inline-block; color:red; } 

Demo

+8
source

You can use CSS classes, for example:

 <div id="contain"> <div style="margin-top:15px;margin-bottom:15px;"> <a href="#" id="A" class="specialLink">A</a> <a href="#" id="B" class="specialLink">B</a> <a href="#" id="C">C</a> </div> </div> 

Then in your CSS you do:

 #contain a.specialLink { margin: 10px 20px 10px 20px; text-decoration: none; display: inline-block; } 

The " .specialLink " part makes it so that only elements with this class receive this style.

+3
source

The first line will apply css to the first two a and the last to skip the tag

 $('#contain').find('a').css('some property'); $('#contain').find('a:last').css('some property'); 
+1
source

if you need to install css for some elements use this code

 $(document).ready(function() { var iterations = 0; var countOfItems = 2; // how many <a> you need to change $('div#contain').find('a').each(function(){ $(this).css({ "margin":"10px 20px 10px 20px", "text-decoration":"none" , "display":"inline-block"}); iterations ++; if(iterations == countOfItems) return false; }); }); 
+1
source

Just use the ID selector:

 #A { ... } 

UPDATE:

You can use nth-child() for CSS3 as follows:

 #contain a:nth-child(number) { css declarations; } 

Where number is the index of the element.

For more information about nth-child() see here .

0
source

U can try -

  <a href="#" id="A" style="margin: 10px 20px 10px 20px; text-decoration: none; display: inline-block;">A</a> <a href="#" id="B" style="margin: 10px 20px 10px 20px; text-decoration: none; display: inline-block;">B</a> <a href="#" id="C" style="different attributes which u want">C</a> 
0
source

All Articles