CSS Selectors

Element, Class, and ID Selectors

In CSS, selectors are patterns used to target specific HTML elements for styling.
Three of the most common types of selectors are element selectors, class selectors, and ID selectors.

Understanding how they work is essential for controlling which elements get styled and how.

1. Element Selector

Definition:

The element selector targets HTML elements directly by their tag name (like h1, p, div, section, etc.).

Syntax:

element-name {
property: value;
}

Example:

p {
color: blue;
font-size: 18px;
}

  • This will apply the styles to all <p> elements in the HTML document.

Use When:

You want to apply styles uniformly to every instance of an HTML tag.

2. Class Selector

Definition:

A class selector targets one or more elements based on a class attribute.
Classes are reusable and can be applied to multiple elements.

Syntax:

.class-name {
property: value;
}

  • Always start the selector with a dot (.) before the class name.

Example:

.button {
background-color: green;
color: white;
padding: 10px 20px;
border-radius: 5px;
}

HTML:

<button class=”button”>Submit</button>
<a href=”#” class=”button”>Learn More</a>

  • Both the <button> and <a> elements will share the same styling because they both have the class button.

Use When:

You want multiple elements to share the same style without affecting unrelated elements.

3. ID Selector

Definition:

An ID selector targets a single, unique element based on its id attribute.
An ID must be unique across the entire HTML document (should not be reused).

Syntax:

#id-name {
property: value;
}

  • Always start with a hash (#) before the ID name.

Example:

#header {
background-color: navy;
color: white;
text-align: center;
}

HTML:

<header id=”header”>
Welcome to My Site
</header>

  • Only the <header> with the ID header will receive these styles.

Use When:

You want to style a unique, single element separately from others.

Selector Priority (Specificity)

  • ID selectors have the highest priority (specificity).
  • Class selectors have medium priority.
  • Element selectors have the lowest priority.

Example: If the same element is targeted by an element selector, a class, and an ID, the ID selector’s styles will apply.

p {
color: black; /* Low priority */
}

.text {
color: blue; /* Medium priority */
}

#special {
color: red; /* High priority */
}

HTML:

<p id=”special” class=”text”>Hello World</p>

  • The text will be red because the ID selector #special wins.

Comparison Table:

Summary Table
Selector Type Syntax Targets Reusability Specificity
Element p {} All <p> tags All elements Low
Class .class {} Any element with class Many elements Medium
ID #id {} Only the unique ID Single element High

Summary:

  • Element selectors apply styles to all instances of a tag.
  • Class selectors apply styles to any elements sharing the same class.
  • ID selectors apply styles to one unique element only.

Understanding and properly using selectors helps you build cleaner, organized, and scalable CSS for your web projects.

Attribute selectors and pseudo-classes (hover, focus, etc.)

CSS offers powerful ways to target elements based on their attributes or user interactions without needing extra classes or IDs.
Two essential features for this are attribute selectors and pseudo-classes like :hover, :focus, and many others.

Mastering these tools makes your styles more dynamic, flexible, and user-friendly.

1. Attribute Selectors

Definition:

Attribute selectors target HTML elements based on the presence or value of their attributes (such as href, src, alt, type, etc.).

Syntax:

element[attribute] {
property: value;
}

element[attribute=”value”] {
property: value;
}

Types of Attribute Selectors:

Summary Table
Syntax Meaning
[attr] Selects elements with the attribute
[attr="value"] Selects elements with an exact value
[attr~="value"] Value in a space-separated list (one word match)
[attr^="value"] Value starts with specified string
[attr$="value"] Value ends with specified string
[attr*="value"] Value contains specified string

Examples:

1. Select all links (<a>) with an href attribute:

a[href] {
color: blue;
}

2. Select only links to external websites:

a[href^=”http”] {
color: green;
}

  • Targets links where href starts with “http”.

3. Select input fields of type “email”:

input[type=”email”] {
border: 2px solid blue;
}

4. Select images with alt text containing “logo”:

img[alt*=”logo”] {
border: 1px solid gray;
}

Best Practice:

Use attribute selectors when you want to style elements based on their function or purpose, without adding extra classes or IDs.

2. Pseudo-Classes

Definition:

Pseudo-classes define a special state of an element.
They allow you to style elements based on user interaction (like hover or focus), their position in the document, or other characteristics.

Syntax:

selector:pseudo-class {
property: value;
}

Common Pseudo-Classes:

Common Pseudo-Classes
Pseudo-Class Meaning
:hover When the user hovers over an element
:focus When an element gains focus (e.g., input box)
:active When an element is being clicked
:visited A link that has already been visited
:first-child Selects the first child of a parent
:last-child Selects the last child of a parent
:nth-child(n) Selects the nth child of a parent

Examples:

1. Change button color on hover:

button:hover {
background-color: orange;
color: white;
}

2. Highlight an input when it is focused:

input:focus {
border-color: green;
outline: none;
}

3. Style the first list item differently:

ul li:first-child {
font-weight: bold;
}

4. Style every odd row in a table:

tr:nth-child(odd) {
background-color: #f9f9f9;
}

Best Practice:

Use pseudo-classes to create interactive and intuitive experiences without needing JavaScript for simple UI feedback.

Combining Attribute Selectors and Pseudo-Classes

You can combine them for advanced, precise styling:

Example: Highlight external links when hovered:

a[href^=”http”]:hover {
text-decoration: underline;
color: red;
}

  • Only external links (href starts with “http”) will change style when hovered.

Summary:

Summary Table:
Feature Purpose
Attribute Selectors Style elements based on their attributes
Pseudo-Classes Style elements based on user interaction or structure

Conclusion:

Attribute selectors and pseudo-classes are key tools for writing smart, dynamic CSS.
They help you style based on context, behavior, and user action, creating more flexible and responsive designs — without cluttering your HTML with extra classes.

Combinators: descendant, child, adjacent sibling, general sibling selectors

In CSS, combinators allow you to select elements based on the relationships between HTML elements.
Instead of targeting elements individually, combinators let you style elements based on their position relative to other elements.

There are four main types of combinators:

1. Descendant Selector (space)

Definition:

The descendant selector selects any element that is inside another element, no matter how deeply nested.

Syntax:

parent descendant {
property: value;
}

Example:

div p {
color: blue;
}

  • This selects all <p> elements that are inside a <div>, whether directly or deeply nested.

HTML Example:

<div>
<p>Paragraph 1</p>
<section>
<p>Paragraph 2</p>
</section>
</div>

  • Both paragraphs will be styled because they are inside the div.

Use When:

  • You want to target all descendants of an element, regardless of how deep.

2. Child Selector (>)

Definition:

The child selector selects only direct children of a specified element.

Syntax:

parent > child {
property: value;
}

Example:

ul > li {
list-style-type: square;
}

  • This selects only <li> elements that are direct children of the <ul>.

HTML Example:

<ul>
<li>Item 1</li> <!– styled –>
<div>
<li>Item 2</li> <!– not styled –>
</div>
</ul>

  • Only “Item 1” will be styled because “Item 2” is nested inside a div inside the ul.

Use When:

You need to strictly control styling for direct children without affecting deeper descendants.

3. Adjacent Sibling Selector (+)

Definition:

The adjacent sibling selector selects an element that is immediately next to another specific element.

Syntax:

element1 + element2 {
property: value;
}

Example:

h2 + p {
margin-top: 0;
}

  • This selects the first <p> that immediately follows an <h2>.

HTML Example:

<h2>Title</h2>
<p>Subtitle</p> <!– styled –>
<p>Another Paragraph</p> <!– not styled –>

  • Only the first <p> right after the <h2> will be styled.

Use When:

You want to style an element only if it comes immediately after a certain other element.

4. General Sibling Selector (~)

Definition:

The general sibling selector selects all siblings of an element that come after the specified element — not just the next one.

Syntax:

element1 ~ element2 {
property: value;
}

Example:

h2 ~ p {
color: green;
}

  • This selects all <p> elements that come after an <h2> in the same parent.

HTML Example:

<h2>Heading</h2>
<p>First paragraph</p> <!– styled –>
<p>Second paragraph</p> <!– styled –>

  • Both <p> elements are styled because they follow the <h2> as siblings.

Use When:

You want to target all sibling elements that come after a certain element.

Comparison Table:

CSS Combinators
Combinator Type Symbol Target Relationship Example
Descendant (space) Any nested element div p
Child > Direct child only ul > li
Adjacent Sibling + Next immediate sibling h2 + p
General Sibling ~ All following siblings h2 ~ p

Visual Diagram of Relationships

Parent
├── Child1
│ ├── Grandchild1 (Descendant)
├── Child2 (Adjacent Sibling of Child1)
├── Child3 (General Sibling of Child1)

  • Child1 > Grandchild1 — Child combinator won’t match; Descendant will.
  • Child1 + Child2 — Adjacent sibling selector will match.
  • Child1 ~ Child3 — General sibling selector will match.

Summary:

  • Descendant Selector (space) — Matches any nested element.
  • Child Selector (>) — Matches direct child only.
  • Adjacent Sibling Selector (+) — Matches the immediately next sibling.
  • General Sibling Selector (~) — Matches all following siblings.

Conclusion

By mastering combinators, you can write more powerful, accurate CSS that targets exactly the elements you want — without unnecessary extra classes or complicated markup.
It leads to cleaner, more efficient, and scalable styling for your web pages.

Would you like a mini real-world project showing combinators in action, like a dynamic FAQ accordion or a styled blog layout?

Pseudo-elements (before, after)

Pseudo-elements in CSS allow you to insert content or style specific parts of elements without adding extra HTML. The most commonly used pseudo-elements are ::before and ::after, which let you inject virtual elements before or after the content of a selected element.

They are incredibly useful for creating decorative elements, icons, tooltips, and UI effects—all without cluttering your HTML markup.

1. Before Pseudo-element

Definition:

Before inserts content before the content of the selected element, as a first child.

Syntax:

selector::before {
content: “text or symbol”;
/* Additional styles */
}

Example:

h1::before {
content: “★ “;
color: gold;
}

HTML:

<h1>Welcome</h1>

Result:

The browser displays: Welcome

Best Use Cases:

  • Adding icons or symbols before headings.
  • Creating custom bullet points.
  • Decorative effects (e.g., quotation marks).

2. After Pseudo-element

Definition:

After inserts content after the content of the selected element, as a last child.

Syntax:

selector::after {
content: “text or symbol”;
/ Additional styles /
}

Example:

a::after {
content: ” “;
color: gray;
}

HTML:

<a href=”https://example.com”>Visit Site</a>

Result:

Displays: Visit Site

Best Use Cases:

  • Appending icons or labels after links or buttons.
  • Adding quotation marks or extra notes.
  • Tooltip-like content (with position and visibility control).

Important Notes:

  • The content property is required for ::before and ::after to display anything.
  • They don’t modify the DOM—only the rendered appearance in the browser.
  • You can apply styling (like color, background, position, display) to the inserted pseudo-element.

Styling Example with Shapes:

.button::before {
content: “”;
display: inline-block;
width: 10px;
height: 10px;
background: green;
border-radius: 50%;
margin-right: 8px;
}

<button class=”button”>Submit</button>

  • Adds a green dot before the button text.

Combined Example – Tooltip Simulation:

.tooltip::after {
content: “This is a tooltip”;
display: none;
background: #333;
color: #fff;
padding: 4px 8px;
position: absolute;
font-size: 12px;
top: 100%;
left: 0;
white-space: nowrap;
}

.tooltip:hover::after {
display: block;
}

<span class=”tooltip”>Hover me</span>

  • Adds a tooltip only when the user hovers over the element.

Key Differences: Pseudo-classes vs. Pseudo-elements

Pseudo-classes vs Pseudo-elements
Feature Pseudo-class (:hover, focus) Pseudo-element (::before, after)
Affects behavior Yes No
Adds content No Yes
Works on sub-parts No Yes
Required property N/A content is required

Summary:

  • Before inserts content before an element’s content.
  • After inserts content after an element’s content.
  • Both are virtual, don’t affect the HTML, and are great for decorations and visual cues.
  • Always use the content property with them.
  • They help keep your HTML clean and your styling modular.

Leave a Comment