Pages

View Pages:

Showing posts with label css. Show all posts
Showing posts with label css. Show all posts

:nth-child and :nth-of-type

:nth-child{}
CSS:
.div1 p:nth-child(2){
   color:#ff0000;
}

:nth-child(2) = select a color for every p element that is the second child of its parent class .div1

HTML:
<div class="div1">
  <p>Lorem ipsum</p>
  <p>Lorem ipsum</p>
  <p>Lorem ipsum</p>
</div>

OUTPUT:
css
now if we insert <h2> tag above the the first paragraph:
<div class="div1">
  <h2>heading</h2>
  <p>Lorem ipsum</p>
  <p>Lorem ipsum</p>
  <p>Lorem ipsum</p>
</div>

OUTPUT:
css
> because the :nth-child selector apply in the second element of the class .div1

:nth-of-type{}
CSS:
.div1 p:nth-of-type(2){  
  color:#ff0000;
}

:nth-of-type(2) = select the second paragraph child of a parent.

HTML:
<div class="div1">
  <p>Lorem ipsum</p>
  <p>Lorem ipsum</p>
  <p>Lorem ipsum</p>
</div>

OUTPUT:
css
now insert again <h2> tag above the the first paragraph:
<div class="div1">
  <h2>heading</h2>
  <p>Lorem ipsum</p>
  <p>Lorem ipsum</p>
  <p>Lorem ipsum</p>
</div>

OUTPUT:
css
> because the :nth-of-type strictly target the second element in your css declaration unlike the nth-child.

for me its ok to use :nth-of-type instead of :nth-child because its less conditional. 

You can also use :nth-child and :nth-of-type via jquery.

css elements and selectors

css elements
div {
      font-family:Arial, Helvetica, sans-serif;
}
.div {
      font-family:Arial, Helvetica, sans-serif;
}
#div {
      font-family:Arial, Helvetica, sans-serif;
}

where:
"div" = is a selector  indicate which element the rule applies to, or HTML element you want to style.
" font-family:Arial, Helvetica, sans-serif;" = is a declaration consists of a
property(font-family:) and a value(Arial, Helvetica, sans-serif;)

some css selectors
*{} = universal selectors

example:
* {
margin:0px;
padding:0px;
}

meaning:
Selects all elements
.{} = class selectors

example:
.graydirt {
margin:0px;
padding:0px;
}
HTML:
<div class="graydirt">1</div>
<div class="graydirt">2......</div>

meaning:
Selects all elements with class="graydirt". Also classes can be used to identify more than one in your documents/pages.
#{} = id selectors

example:
#graydirt {
margin:0px;
padding:0px;
}
HTML:
<div id="graydirt">1</div>

meaning:
Selects the element with id="graydirt". Also ID can be used to identify one element in your document/page.
li > a = child selectors

example:
li > a {
color:#ff0000;
}

HTML:
<ul>
   <li><a href="#">lorem</a>
         <div><a href="#">lorem2</a></div>
   </li>
</ul>

output:
lorem
lorem2

meaning:
Targets only the first "a" elements that are children of an "li" element (but not other "a" elements inside the "li").
li a = descendant selectors

example:
li a {
margin:0px;
padding:0px;
}

HTML:
<ul>
   <li><a href="#">lorem</a>
         <div><a href="#">lorem2</a></div>
   </li>
</ul>

output:
lorem
lorem2

meaning:
Targets all "a" elements inside the "li".