Pseudo-elements and Classes in CSS

While HTML defines the structure of your webpage, CSS brings it to life with styles. But sometimes, styling basic elements isn’t enough. That’s where pseudo-elements and classes come in! They allow you to target specific parts of elements or create dynamic styles based on element states.

Pseudo-classes:

  • Target elements based on their state (e.g., hovered over, focused, visited).
  • Use a colon (:) followed by the pseudo-class name.
  • Examples:
    • :hover: Changes style when hovered over (e.g., button color).
    • :focus: Applies styles when focused (e.g., input border).
    • :checked: Styles checked form elements (e.g., radio button).

Example:

CSS

.button {
  background-color: #ccc;
  padding: 10px;
}

.button:hover {
  background-color: #007bff;
  color: white;
}


Pseudo-elements:

  • Target specific parts of an element (e.g., first letter, first line).
  • Use two colons (“::”) followed by the pseudo-element name.
  • Examples:
    • ::first-letter: Styles the first letter of an element.
    • ::first-line: Styles the first line of an element.
    • ::before: Inserts content before the element’s content.
    • ::after: Inserts content after the element’s content.

Example:

CSS

p::first-letter {
  font-size: 2em;
  color: red;
}

blockquote::before {
  content: ">";
  font-size: 3em;
  margin-right: 10px;
}


Classes:

  • User-defined keywords to group elements with similar styles.
  • Apply styles to elements with the same class using a dot (.) followed by the class name.
  • Examples:
    • .important: Important text (bold, red).
    • .highlight: Highlighted text (yellow background).
    • .button: Standard button styles.

Example:

HTML

<p class="important">This is important!</p>
<span class="highlight">This is highlighted.</span>
<button class="button">Click me!</button>

CSS

.important {
  font-weight: bold;
  color: red;
}

.highlight {
  background-color: yellow;
}

.button {
  /* Button styles here */
}


Key Differences:

FeaturePseudo-classPseudo-elementClass
TargetStatePart of elementUser-defined
Syntax: keyword:: keyword. keyword
Example:hover::first-letter.important

Remember:

  • Pseudo-classes and pseudo-elements cannot create new elements; they style existing ones.
  • Classes offer more flexibility for grouping and reusability.
  • Combine them strategically for powerful and efficient CSS styling!

Leave a Reply

Your email address will not be published. Required fields are marked *