DEV Community

ENDEESA
ENDEESA

Posted on

CSS Selectors - Summary

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)...
}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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'
}
Enter fullscreen mode Exit fullscreen mode

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>

Enter fullscreen mode Exit fullscreen mode

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>

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

  • 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>

Enter fullscreen mode Exit fullscreen mode

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay