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
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; } 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; } +8
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
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
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