loading...

CSS Selectors - Summary

banzyme2 profile image EN_DEE_SA ・2 min read

1. Tag / Element selector

  • Use the built-in html element name, e.g. div, body, span, p, ul etc.
body
{
 // style applies entire body(including child tags)...
}

2. Descendant selector


<p>
  <a>direct descendant</a>

  <span><a>Indirect descendant</a></span>
</p>

<style>
p a
{
  // Apply styles to all 'a'(anchor) elements withing the paragraph p
}
</style>

3. Child selector

<p>
  <a>direct descendant</a>

  <span><a>Indirect descendant</a></span>
</p>

<style>
p > a
{
  // Apply styles to direct descendant only!
}
</style>

4. Attribute selector

  • Select an element with a specified attribute

p[id]
{
  // Apply styles to p element with id attribute set to anything
}


p[id='fist']
{
  // Apply styles to p element with id attribute set to 'first'
}

5. Select by Id

  • Probably the most common selector ??
<body>
<div id="container"></div>
<div id="not_a_container"></div>
</body>

<style>

 #container
  {
   // style applies to div with id attribute set to 'container'
  }
</style>


6. Select by Class

  • Second most common? No ? Ok.
<body>
<div class="container"></div>
<div class="not_a_container"></div>
</body>

<style>

 .container
  {
   // style applies to div with class attribute set to 'container'
  }
</style>


7. Pseudo selectors

  • Typically used to apply styles based on user events e.g. On mouse hover

a:hover
{
  font-weight: bold;
}

// set the font weight of all links to bold on mouse hover


  • And finally......

8. Nth Child Selector

  • This is best explained using an example

<div>
<p>
Fist
</p>

<p>
Second
</p>

<p>
Third
</p>


<p>
Fourth
</p>
</div>


<style>
p:nth-child(2n)
{
 color: red;
}

// This will affect each p element inside the parent div who's position is a //multiple of 2
</style>

Discussion

pic
Editor guide