Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply CSS on particular <a> in a div

So i have following div in HTML. Now I was wondering is there a way to apply CSS to just first 2 <a> and different Css on 3rd <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 above Css to only first 2 <a> in Div.

Thanks for help. :)

like image 545
Richa Avatar asked Apr 18 '14 06:04

Richa


People also ask

How do I apply a CSS to a specific div?

There is no way to "link a css file to a specific div". You can make the css in style. css apply only to a certain div using selectors, but your question, as stated, makes no sense.

Can we use CSS in div tag?

The <div> tag is used as a container for HTML elements - which is then styled with CSS or manipulated with JavaScript. The <div> tag is easily styled by using the class or id attribute. Any sort of content can be put inside the <div> tag!

How do I apply a CSS to a specific class?

To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class. To do this, start with the element name, then write the period (.)

How do I apply CSS to an element?

CSS can be added to HTML documents in 3 ways: Inline - by using the style attribute inside HTML elements. Internal - by using a <style> element in the <head> section. External - by using a <link> element to link to an external CSS file.


1 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

like image 144
Milind Anantwar Avatar answered Sep 19 '22 12:09

Milind Anantwar