CSS Selectors

Basic Selectors (Element, ID, Class)

Basic selectors target elements directly:

  • Element Selector: Selects all instances of a tag (e.g., p, div).
  • ID Selector: Selects a single element using #id.
  • Class Selector: Selects elements with a specific class using .class.
<style>
  p {
    color: blue;
  }

  #main-heading {
    font-size: 24px;
  }

  .highlight {
    background-color: yellow;
  }
</style>

<h1 id="main-heading">Welcome</h1>
<p>This is a paragraph.</p>
<p class="highlight">This is a highlighted paragraph.</p>

Welcome

This is a paragraph.

This is a highlighted paragraph.

Grouping and Universal Selector

Grouping Selector (,): Targets multiple selectors at once.
Universal Selector (*): Applies to all elements.

<style>
  h2, p {
    color: darkgreen;
  }

  * {
    font-family: Arial, sans-serif;
  }
</style>

<h2>Grouped Selector</h2>
<p>Paragraph with grouped styling.</p>
<div>This div has default font from universal selector.</div>

Grouped Selector

Paragraph with grouped styling.

This div has default font from universal selector.

Combinators (descendant, child, sibling)

CSS provides combinators to select elements based on their relationship:

  • Descendant (div p): Targets p inside div.
  • Child (div > p): Targets only direct children.
  • Adjacent sibling (h2 + p): Targets first p after h2.
  • General sibling (h2 ~ p): Targets all ps after h2.
<style>
  div p {
    color: blue;
  }

  div > p {
    font-weight: bold;
  }

  h2 + p {
    background-color: #f9f9a0;
  }

  h2 ~ p {
    font-style: italic;
  }
</style>

<div>
  <p>Direct child of div</p>
  <section>
    <p>Descendant inside section</p>
  </section>
</div>

<h2>Heading</h2>
<p>This is adjacent sibling.</p>
<p>This is general sibling.</p>

Direct child of div

Descendant inside section

Heading

This is adjacent sibling.

This is general sibling.

Attribute Selectors

Attribute selectors allow you to style elements based on the presence or value of attributes.

<style>
  input[type="text"] {
    border: 2px solid green;
  }

  a[target="_blank"] {
    color: red;
  }
</style>

<input type="text" placeholder="Text input">
<input type="password" placeholder="Password input">
<a href="#" target="_blank">Open in new tab</a>

Pseudo-classes and Pseudo-elements

Pseudo-classes style elements based on user interaction or element state.
Pseudo-elements style specific parts of an element.

<style>
  a:hover {
    color: orange;
  }

  p::first-line {
    font-weight: bold;
  }

  p::before {
    content: "👉 ";
  }
</style>

<a href="#">Hover over me</a>
<p>This is a paragraph demonstrating pseudo-elements.</p>
Hover over me (hover to see effect)

👉 This is a paragraph demonstrating pseudo-elements.

If you have any questions, feel free to ask. Thank you for reading!

Thankyou!