Sunday, November 18, 2012

CSS Selectors


Here is the list of useful CSS selectors.


> Sign:

> Symbol target elements which are direct children of a parent element.

HTML

<div id="container">
   <p>First</p>
    <div>
        <p>Child Paragraph</p>
    </div>
   <p>Second</p>
   <p>Third</p>
</div>​

CSS

div#container > p {
  border: 1px solid black;
}


It will target all P elements which are direct children of parent div, not children of child div.


+ Sign:

This sign is adjacent sibling combinator.
The elements in the selector have the same parent, and the second one must come immediately after the first.
For example let’s say you want to add text-color for all p tags which comes inside the child div but not inside the main parent div.

HTML
<div id="container">
   <p>First</p>
    <div>
        <p>Child Paragraph</p>
    </div>
   <p>Second</p>
   <p>Third</p>
</div>​

CSS
div + p {
   color: red; font-weight:bold
}



~ Sign:

This is general sibling combinator and similar to Adjacent sibling combinator. The difference is that the second selector does NOT have to immediately follow the first one means It will select all elements that is preceded by the former selector.

HTML
<div id="container">
   <p>First</p>
    <div>
        <p>Child Paragraph</p>
    </div>
   <p>Second</p>
   <p>Third</p>
</div>​

CSS
div ~ p{
background-color:blue; color:white
}



:NTH-CHILD

The :nth-child() pseudo-class can be used to target one or more specific children of parent element.
For example if you want to give different style only for the particular li item then you can do it with nth-child

HTML

<ul>
  <li>Link 1</li>
  <li>Link 2</li>
  <li>Link 3</li>
  <li>Link 4</li>
  <li>Link 5</li>
</ul>

CSS

ul li:nth-child(3) {
    color: red;
  }


Likewise below are the other methods of the nth-child() pseudo-class.


:NTH –CHILD()

:nth-child(odd) and :nth-child(even)
This method adds styles to alternative elements.

HTML

<ul>
    <li>test</li>
    <li>test</li>
    <li>test</li>
    <li>test</li>
    <li>test</li>
</ul>​

CSS

li:nth-child(odd){
    background-color:green; color:white
}
li:nth-child(even){
    background-color:yellow;
}​



No comments:

Post a Comment