Isaac.

web

CSS Selectors Introduction

Master CSS selectors to target HTML elements precisely.

By Emem IsaacAugust 13, 20232 min read
#css#selectors#styling#specificity
Share:

A Simple Analogy

CSS selectors are like finding people in a crowd. You can pick by name (class), ID, appearance (element), or relationships.


Why Selectors?

  • Targeting: Apply styles to specific elements
  • Efficiency: Avoid inline styles
  • Maintainability: Change styles centrally
  • Performance: Optimize with specific selectors
  • Flexibility: Target any element

Basic Selectors

/* Element selector */
p { color: blue; }

/* Class selector */
.highlight { background: yellow; }

/* ID selector */
#main { font-size: 24px; }

/* Attribute selector */
input[type="text"] { border: 1px solid blue; }

/* Attribute value selector */
a[href*="example.com"] { color: green; }

Combinators

/* Descendant (space) */
div p { color: red; }

/* Child (>) */
ul > li { list-style: none; }

/* Adjacent sibling (+) */
h1 + p { margin-top: 0; }

/* General sibling (~) */
p ~ p { margin-top: 16px; }

Pseudo-Classes

a:hover { color: red; }
input:focus { border: 2px solid blue; }
li:first-child { font-weight: bold; }
li:last-child { border-bottom: none; }
p:nth-child(odd) { background: #f0f0f0; }

Best Practices

  1. Specificity: Use lowest needed
  2. Performance: Avoid deep nesting
  3. Reusability: Use classes for styles
  4. Clarity: Name classes semantically
  5. Avoid !important: Use specificity instead

Related Concepts

  • CSS specificity
  • CSS cascade
  • CSS Grid
  • Flexbox

Summary

Use CSS selectors to target elements precisely. Master combinators, pseudo-classes, and attribute selectors.

Share:

Written by Emem Isaac

Expert Software Engineer with 15+ years of experience building scalable enterprise applications. Specialized in ASP.NET Core, Azure, Docker, and modern web development. Passionate about sharing knowledge and helping developers grow.

Ready to Build Something Amazing?

Let's discuss your project and explore how my expertise can help you achieve your goals. Free consultation available.

💼 Trusted by 50+ companies worldwide | ⚡ Average response time: 24 hours