✅ Module 2: CSS Syntax and Selectors (🧩🔍)

🧩 Module 2: CSS Syntax and Selectors

CSS works by targeting HTML elements and applying styles to them using a syntax composed of selectors and declarations. This module will help you understand how CSS rules are written and how to target the right elements effectively.

🧠 Basic Syntax

CSS syntax follows a simple pattern:

selector {
  property: value;
}

Example:

h1 {
  color: blue;
  font-size: 24px;
}

In the above example, the selector h1 targets all <h1> elements and applies a blue color and a font size of 24 pixels. 🎨

🔎 CSS Selectors Explained

Selectors are used to \"select\" the HTML elements you want to style. There are various types of selectors for different purposes:

  • Universal Selector (*): Targets all elements
    * { margin: 0; padding: 0; }
  • Type Selector: Targets elements by tag name
    p { line-height: 1.5; }
  • Class Selector (.className): Targets elements with a specific class
    .box { padding: 20px; }
  • ID Selector (#idName): Targets an element with a specific ID
    #header { background: black; }
  • Group Selector: Targets multiple elements
    h1, h2, h3 { font-family: sans-serif; }
  • Attribute Selector: Targets elements with certain attributes
    input[type=\"text\"] { border: 1px solid gray; }

🎯 Advanced Selectors

  • Pseudo-Classes – Apply styles based on element state:
    a:hover { color: red; } (when mouse is over a link)
    input:focus { border-color: blue; } (when input is selected)
  • Pseudo-Elements – Style specific parts of elements:
    p::first-letter { font-size: 200%; }
    div::before { content: '👉'; }
  • Combinators – Define relationships between elements:
    • div p: All <p> inside <div> (descendant)
    • ul > li: Direct children <li> of <ul> (child)
    • h1 + p: Paragraph immediately after <h1> (adjacent sibling)
    • h1 ~ p: All paragraphs that are siblings of <h1> (general sibling)

🛠️ Best Practices

  • Use classes for reusable styles across multiple elements.
  • Use IDs sparingly – they're meant to be unique.
  • Group selectors to reduce repetition.
  • Use attribute selectors and pseudo-classes for interactive styles.

✅ Real-Life Example

Imagine you’re building a blog. You can style all titles with a class like .post-title, apply different colors on hover for links using :hover, and display icons before elements using ::before. With smart use of selectors, you can build scalable and maintainable designs. 📖

📌 Summary

  • CSS rules consist of selectors and declarations.
  • There are many types of selectors to precisely target HTML elements.
  • Pseudo-classes and pseudo-elements allow you to style dynamic and partial content.
  • Mastering selectors is essential for writing efficient and powerful CSS. 💪

Post a Comment

0 Comments