css pseudo class Essentials for Web Developers

Author

Posted Nov 1, 2024

Reads 632

Abstract minimalist design featuring white and green spheres with geometric shapes on a white background.
Credit: pexels.com, Abstract minimalist design featuring white and green spheres with geometric shapes on a white background.

As a web developer, understanding CSS pseudo-classes is crucial for creating interactive and dynamic web pages.

CSS pseudo-classes allow you to select and style elements based on user interactions, such as hover and focus.

They can also be used to style elements based on their state, like active and visited links.

For instance, the :hover pseudo-class is used to style an element when the user hovers over it.

The :focus pseudo-class is used to style an element when it receives focus, such as when a user clicks on it.

Pseudo-classes can also be used to style elements based on their content, like the :empty pseudo-class.

This pseudo-class is used to select elements that have no content.

You can also use pseudo-classes to style elements based on their position in the document, like the :first-child pseudo-class.

This pseudo-class is used to select the first child element of a parent element.

Pseudo-Elements

Pseudo-elements are like virtual elements that we can treat like regular HTML elements. They don't exist in the document tree or DOM, which means we don't actually type pseudo-elements in the HTML, but rather create them with CSS.

Credit: youtube.com, CSS Pseudo-classes: in 100 Seconds

The double colon (::) and single colon (:) difference is merely a visual distinction between CSS 2.1 and CSS3 pseudo-elements. You are free to use either.

Some examples of pseudo-elements include ::after, ::before, and ::selection. We can use these pseudo-elements to style specific parts of elements, like adding a placeholder text or a selection highlight.

Here are some examples of pseudo-elements:

  • ::after
  • ::before
  • ::selection
  • ::placeholder (experimental)

Pseudo-Elements

Pseudo-Elements are like virtual elements that we can treat like regular HTML elements. They don't exist in the document tree or DOM, which means we don't actually type pseudo-elements in the HTML, but rather create them with CSS.

You can create pseudo-elements using a double colon (::) or a single colon (:), but the difference is just a visual distinction between CSS 2.1 and CSS3 pseudo-elements. You're free to use either.

Pseudo-elements are used to style specific parts of elements. For example, you can use the ::after pseudo-element to add content after an element, and the ::before pseudo-element to add content before an element.

Credit: youtube.com, Before and After pseudo elements explained - part one: how they work

Some pseudo-elements are experimental, meaning their specification is not stable or finalized. These include ::backdrop, ::fullscreen, and ::placeholder. To use these pseudo-elements, you'll need to refer to Can I Use and use an auto-prefixing tool like -prefix-free or Autoprefixer.

Here's a list of some pseudo-elements, including the experimental ones:

  • ::after
  • ::before
  • ::backdrop (experimental)
  • ::fullscreen (experimental)
  • ::placeholder (experimental)

These pseudo-elements can be used to add unique styles to specific parts of your elements, giving you more control over the layout and design of your web pages.

Visited

The :visited pseudo-class is used to style links that have been visited by the user.

It's a special state for an element that can be used to change the appearance of a link once it's been clicked on. You can only style a limited set of properties with :visited, including color, background-color, border-color, outline-color, and the color of SVG fill and stroke.

This pseudo-class is positioned second in order, after the :link pseudo-class, and can be applied to any HTML element, not just links.

You might enjoy: Link a Css File Html

Credit: youtube.com, :visited - CSS Pseudo Selector !

I've noticed that some websites use :visited to create a visual cue for links that have already been visited, like the purple color on Google search results.

You can use :visited to create a unique style for links that have been visited, but keep in mind that it's limited in its functionality for security reasons.

Curious to learn more? Check out: Create Css Selector from Webpage

If you work with CSS preprocessors, such as Sass, you might find the Sass mixin for links particularly useful.

This mixin optimizes our workflow by forcing us to declare all four states of our links.

The mixin doesn't declare any defaults in its arguments, so we're required to specify each state individually.

The :focus and :active pseudo-classes are typically declared together, but feel free to separate them if you prefer.

This mixin can be used to create a basic set of links, and it's a great way to streamline your workflow when working with Sass.

First-Child and Last-Child

Credit: youtube.com, CSS pseudo-element: first-child last-child

The :first-child and :last-child pseudo-classes are super useful for targeting the first or last item in a group of sibling elements. They can be used together to achieve this, as seen in the example where the first and last li elements are targeted.

The :first-child pseudo-class represents the first child of its parent element. In the example, the first li element will be the only one with orange text. This is because the :first-child pseudo-class specifically targets the first element in the group.

The :last-child pseudo-class represents the last child element in its parent container. In the example, the last li element will be the only one with orange text. This shows how :last-child can be used to target the last item in a group of sibling elements.

Using the :first-child and :last-child pseudo-classes together allows you to target both the first and last item in a group. This can be useful for styling or selecting elements in a specific way.

Nth-child and Nth-of-Type

Credit: youtube.com, nth-of-type vs. nth-child - CSS Selectors

The :nth-child and :nth-of-type pseudo-classes are incredibly versatile and powerful tools in CSS. They allow you to target specific elements based on their position in the markup.

The :nth-child pseudo-class takes an argument, which is a formula that we type in parentheses. This formula can be a single integer, a formula structured as an+b, or the keyword odd or even.

You can select the second child with :nth-child(2). This will only apply the style to the element that is in the second position in the markup.

The :nth-child pseudo-class can also be used to select every other child starting from the second, by using :nth-child(2n+1). This will apply the style to the elements that are in the second, fourth, sixth, and so on, positions in the markup.

You can also use the an+b microsyntax to select elements at regularly spaced intervals. For example, :nth-child(3n+3) will select every third item, starting at item 3.

Credit: youtube.com, nth-child() just got an upgrade

Here are some examples of how to use the :nth-child pseudo-class:

  • :nth-child(2) - Select the second child
  • :nth-child(2n+1) - Select every other child starting from the second
  • :nth-child(3n+3) - Select every third item, starting at item 3

The :nth-of-type pseudo-class works similarly to :nth-child, but it's more specific because you're targeting a specific element relative to like elements contained within the same parent element.

Additional reading: Css Hide Class

Target

The :target pseudo-class is a powerful tool that lets you target a unique ID of an element and the hash in the URL.

You can use it to make a link jump to a specific element on the same page, rather than taking you to another page. This is done by using the # symbol and the element ID as an href attribute for your link.

The :target pseudo-class can be used with anchors, which are powerful elements that have become even more so with the introduction of smooth-scrolling and scroll-padding-top.

You can use the background shorthand instead of background-color to achieve the same result with the :target pseudo-class.

By using the :target pseudo-class, you can stylize the targeted element, such as adding an outline to a paragraph.

Empty

Credit: youtube.com, Difference Between :empty And :blank Pseudo Selectors In CSS !

The :empty pseudo-class targets elements that have no content in them of any kind at all.

An element is considered empty if it has no children, including text nodes. This means that even a space would be considered content, making the element not empty.

You can use the :empty pseudo-class to hide elements that have no content, which is useful in certain scenarios.

For example, if you have a div in which you dynamically add content using JavaScript, you can use the :empty pseudo-class to hide the div if there's no content.

Here are some examples of what is considered empty and not empty:

  • Empty: No content or characters would appear in an element.
  • Not empty: Characters would appear inside the element, even a space.

The :empty pseudo-class can be useful if you have little control over the HTML and want to hide empty elements, such as a stray, empty paragraph added by a WYSIWYG content editor.

Where()

The :where() pseudo-class is a game-changer for selecting elements. It takes a list of selectors as an argument and selects elements that can be selected by any of the selectors in that list.

For more insights, see: List Styling in Css

Credit: youtube.com, Learn CSS Pseudo Elements In 8 Minutes

It's almost similar to :is(), but with a key difference in specificity. :where() always has a specificity of 0, which can affect the outcome of style rules.

For example, if you use :where() to select an image and add a blue border, and then use the img selector to set an orange border, the orange border will win out because :where() has 0 specificity.

The :where() pseudo-class can be a useful tool in certain situations, but it's essential to understand its limitations and how it interacts with other selectors.

Recommended read: Border for Text in Css

Link states are a crucial aspect of CSS pseudo-classes, and understanding them can help you create more effective and user-friendly designs.

The :link pseudo-class represents the "normal" state of links and is used to select links that have not yet been visited. It should be declared before all other pseudo-classes in this category.

You can use the :visited pseudo-class to target any link that a user has visited, and it's commonly used to style visited links with a different color or design.

Credit: youtube.com, Learn CSS pseudo-classes in 7 minutes! ☟

The order of the four pseudo-classes for links is recommended to be: :link, :visited, :hover, and :active.

By using the :any-link pseudo-class, you can apply the same styles to both links and visited links without repeating the styles.

Here are the four pseudo-classes for links in the recommended order:

  1. :link
  2. :visited
  3. :hover
  4. :active

The :hover pseudo-class is used to target an element hovered over by the mouse, and it's commonly used to style links, buttons, and other clickable elements.

The :focus pseudo-class is often used to target a field the user clicked or tabbed into, and it's super useful for form fields and buttons.

The :active pseudo-class is used when a click is being made or held, and it provides excellent visual feedback to the user.

Note that the :focus pseudo-class is used for accessibility concerns, and removing its default outline should be done with caution.

Link Styling is a crucial aspect of CSS pseudo-class, and it all starts with the :link pseudo-class. This pseudo-class represents the normal state of links and is used to select links that have not yet been visited.

Expand your knowledge: Css Link to Stylesheet

Credit: youtube.com, Styling Links with Pseudo Classes

The order of all four pseudo-classes is recommended to be :link, :visited, :hover, :active. This is a best practice to follow for optimal styling results.

The :visited pseudo-class targets any link that a user has visited, and it's commonly used to style visited links differently. You can also use the :link pseudo-class to target non-visited links.

Pseudo-Class Selectors

Pseudo-Class Selectors are a powerful tool in CSS that allow you to select elements based on various conditions. They can be used to target elements based on their relationship to others, their position in the document, or even their state of being active or hovered over.

Some common types of pseudo-class selectors include relative selectors, which target elements based on their position in the document, and structural pseudo-classes, which target additional information in the document tree or DOM.

Here are some examples of pseudo-class selectors:

  • :first-child and :last-child select an element's first or last child.
  • :nth-child(even) selects even elements.
  • :target selects an element that is being targeted by an anchor link.
  • :not selects elements that do not match a certain condition.
  • :hover selects an element when it is being hovered over.
  • :active selects an element when it is being clicked or tapped.
  • :only-of-type selects the only element of a certain type in a group of siblings.

These are just a few examples of the many pseudo-class selectors available in CSS. By using these selectors, you can create complex and dynamic styles that respond to user interactions and document structure.

Colon Usage

Credit: youtube.com, The new CSS pseudo-classes explained - :is() :where() :has()

The double colon (::) is recommended for pseudo-elements that require it, such as ::backdrop, as it's the only notation they accept.

While some pseudo-elements like ::before and ::after can use either single or double colon notation, it's generally a good idea to use double colon notation for pseudo-elements that require it, like ::backdrop.

The specification recommends using single-colon notation for pseudo-elements that support both notations, as it ensures backwards compatibility with legacy browsers.

I personally use single-colon notation in my CSS to ensure backwards compatibility, but I make sure to use double-colon notation for pseudo-elements that require it.

All browsers support double colons for pseudo-elements except Internet Explorer 8 and below.

On a similar theme: Css Double Class

Hover

Hover is a pseudo-class that allows you to style an element when the user's pointer is above it. It's not just for links, although that's the most common use case.

The :hover pseudo-class is used to style an element when the user's pointer is above it. This can be a useful way to hint that an element can be interacted with. If a user has a pointing device like a mouse or trackpad, and they place it over an element, you can hook on to that state with :hover to apply styles.

Take a look at this: Html Image Text on Hover

Credit: youtube.com, CSS - The Hover Pseudo Class

You can use the :hover pseudo-class to style any element, not just links. It's a versatile tool that can help you create interactive and engaging user interfaces.

Here are some key facts about the :hover pseudo-class:

  • It's used to style an element when the user's pointer is above it.
  • It can be triggered by a pointing device like a mouse or trackpad.
  • It's not just for links, although that's the most common use case.

I've used the :hover pseudo-class in my own projects to create hover effects that enhance the user experience. By applying styles when the user's pointer is above an element, you can create a sense of interactivity and draw attention to important elements on the page.

Selectors

Relative selectors are a powerful tool in CSS, and they're used to select elements based on their position in the DOM. They're a type of structural pseudo-class that targets elements based on their relationship to others.

The :first-child and :last-child pseudo-classes are used to select an element's first or last child, respectively. For example, you can use :first-child to style the first element in a list.

You can also use the :nth-child pseudo-class to select elements based on their index in the DOM. The :nth-child(even) selector, for instance, selects even elements.

Here's an interesting read: Css Selector for First Sibling

Credit: youtube.com, Do you know the difference? pseudo-classes vs pseudo-elements

Another useful pseudo-class is :first-of-type, which represents the first element of its kind in its parent container. This is different from :first-child, which selects the first child regardless of its type.

The :last-of-type pseudo-class works similarly, but it selects the last element of its kind in its parent container. This can be useful when you want to style the last element of a particular type in a list.

You can also use the :only-of-type pseudo-class to select the only element of a certain type in a group of siblings. This is useful when you want to style lists with only one item or find the only bold element in a paragraph.

The :not pseudo-class is another useful tool that allows you to declare what you do not want in your selector. This can make your selectors cleaner and more descriptive.

The :only-child pseudo-class targets the only child of a parent element, making it a useful tool for styling lists or other elements with a single child.

Modern CSS pseudo-class selectors offer a range of new features compared to older selectors. They allow you to target elements based on their relationship to others or select elements based on more complex conditions.

Intriguing read: Child Selector Css

Nth-last-child

Credit: youtube.com, :nth-last-child - CSS Pseudo Selector Explained !

The :nth-last-child pseudo-class is a powerful tool for selecting elements based on their position from the end of a list. It works similarly to :nth-child, but starts counting from the end instead of the beginning.

To select the second child from the end, use :nth-last-child(2). This will only target the "Iota" element, making it orange.

You can also use :nth-last-child to select every other child, starting with the second from the end, by using an even number like :nth-last-child(2n). This will target "Iota", "Eta", "Epsilon", "Gamma", and "Alpha", making them orange.

For even children, starting from the end, use :nth-last-child(even). This will target all even elements in the list.

Here are some examples of how to use :nth-last-child:

Keep in mind that some pseudo-classes may not work well with all HTML elements, so be sure to test them in different contexts.

Checked

The :checked pseudo-class is a powerful tool for web designers and developers. It targets radio buttons, checkboxes, and option elements that have been checked or selected.

Credit: youtube.com, CSS Style form elements ( :checked pseudo-class )

This pseudo-class is available when a supporting form element, such as a checkbox or radio button, is in a checked state. A checkbox or radio button can be in one of three states: checked, unchecked, or indeterminate.

A checkbox or radio button can be in an indeterminate state when it's neither checked nor unchecked. This is often used in cases like a "select all" control that checks all checkboxes in a group. If the user unchecks one of these checkboxes, the root checkbox should be put into an indeterminate state.

The :checked pseudo-class can be used to style the label of a checkbox or radio button when it's checked. For example, you can use CSS to highlight the label when the checkbox is selected.

Here are some examples of how the :checked pseudo-class can be used:

The :checked pseudo-class is a useful tool for creating interactive and engaging web experiences. By using it, you can enhance the user experience and make your web application more user-friendly.

A unique perspective: Responsive Web Design with Html 5

Read-Write

Credit: youtube.com, :read-write / :read-only Pseudo Selectors In CSS Explained !

The :read-write pseudo-class is a powerful tool for styling editable elements. It matches elements that are either editable by default or have the contenteditable attribute set to true.

Elements like inputs and textareas are editable by default, but others like div and p are not. Adding the contenteditable attribute to any element makes it editable.

The :read-write pseudo-class allows us to specify styles specifically for editable elements. It works for elements that are editable by default, as well as those made editable with the contenteditable attribute.

In Chrome, support for the :read-write pseudo-class is limited to inputs and textarea fields from version 15 to 35, but it's fully supported from version 36. Safari has similar support, but only for inputs and textarea fields from version 4 to 8, and fully from version 9.

Firefox supports the :read-write pseudo-class from version 3 to 77 using the -moz prefix, and fully from version 78.

With the :read-write pseudo-class, we can provide visual feedback for users who can edit content, making the user experience even better.

A unique perspective: Css Attr Selector

Required & Optional

Credit: youtube.com, CSS Style form elements ( :Required and :optional pseudo classes )

In HTML, you can use the required attribute on an input to indicate its need to be filled before submitting the form. This attribute is essential for ensuring that users provide necessary information.

You can then use the :required pseudo-class to target those elements and put an emphasis on them. For example, if an input field has the required attribute, you can style it with CSS to give a visual cue that the field is required.

The :optional pseudo-class is also provided by CSS to target inputs that are not required. This allows you to differentiate between required and optional fields in your forms.

Here's a quick rundown of the pseudo-classes related to form fields:

By using these pseudo-classes, you can create more intuitive and user-friendly forms that clearly indicate which fields are required and which are optional.

Read-Only

The :read-only pseudo-class targets an element that cannot be edited by the user.

It's similar to the :disabled pseudo-class, and the attribute used in the markup determines which pseudo-class to use.

Credit: youtube.com, CSS PSEUDO CLASS | read-only | read-write | target | root

This pseudo-class is useful in forms where we need to show pre-populated information that cannot be altered but still needs to be displayed within the form element for submission purposes.

In these cases, we can use the :read-only pseudo-class to give the element gray text, as seen in the example by Ricardo Zea on CodePen.

The :read-only CSS pseudo-class represents an element that is not editable by the user, meaning its value cannot be changed.

This selector can be used to apply styles to elements that have the readonly attribute or have been dynamically set to be read-only through JavaScript.

The :read-only pseudo-class removes all the styling that makes the inputs look like clickable fields, making them look like read-only paragraphs.

Read-only and read-write pseudo-classes are partially supported in Chrome from version 15 to 35, but fully supported from version 36.

Firefox supports them from version 3 to 77 using the prefix -moz and fully supports from version 78.

Safari has support from versions 4 to 8 only for inputs and textarea fields and supports fully from version 9.

Lang

Credit: youtube.com, :lang() Pseudo Class Selector In CSS Explained !

The :lang pseudo-class is used to match the language of an element, which is determined by a combination of the lang="" HTML attribute, the corresponding meta element, and information from the protocol.

This pseudo-class is commonly used in the html tag, but it can also be applied to any other tag if needed.

The lang="" attribute is used to declare the language of an element, as seen in German quotation marks added by a browser's UA, which look like „Lorem ipsum dolor sit amet.“

However, when quotation marks are declared via CSS, German quotation marks can look like »Lorem ipsum dolor sit amet.«, which is also correct.

Root

The :root pseudo-class is a powerful tool in CSS, and it's essential to understand how it works.

In virtually all cases, :root will refer to the html element in an HTML document.

You can use :root to target the highest parent element in an HTML document, which is the html element.

Note that using html as the selector would have the same effect, but :root has a higher specificity than an element selector.

Has()

Credit: youtube.com, CSS Useful Features - Has Pseudo Class

The :has() pseudo-class is a powerful tool for selecting elements based on their descendants. It's like a detective on a mission to find specific elements based on the clues of their children.

This pseudo-class allows you to select elements that have a certain descendant element, making it super useful for styling specific parts of your HTML document. For example, you can use :has() to give a unique style to list items that have an extra emphasis, represented by a span element.

The :has() pseudo-class is supported in modern browsers, with Chrome offering support from version 105 and Safari from version 15.4. However, earlier versions of Firefox do not support it by default.

To enable :has() in Firefox, you need to flip the layout.css.has-selector.enabled flag to true. This will allow you to use the :has() pseudo-class in your CSS code.

Here are some examples of how to use the :has() pseudo-class:

  • Selecting li elements that have a span descendant: :has(li > span)
  • Selecting figure elements that have a figcaption within them: :has(figure > figcaption)

Note that the :has() pseudo-class has some unique features, such as being able to group multiple selectors without worrying about the whole rule breaking just because of one small mistake.

Finding Empty Elements

Credit: youtube.com, The :empty Pseudo Class

Finding empty elements can be a real challenge, especially when you're trying to hide them from view. The :empty pseudo-class is a great tool for this job.

An element is considered empty if it has no content of any kind, including text, HTML elements, or even whitespace. This means that if there's a space between the opening and closing tags, the element won't be considered empty.

You can use the :empty pseudo-class to hide elements that have no content, such as a stray paragraph added by a WYSIWYG content editor. This can be really useful if you have little control over the HTML.

Here are some examples of elements that are considered empty:

  • An element with no content or characters
  • An element with only an HTML comment
  • An element with only whitespace

On the other hand, the following elements are not considered empty:

  • An element with text
  • An element with another HTML element
  • An element with a space (yes, even a single space counts as content!)

If you're trying to hide empty elements, you can use the :empty pseudo-class in your CSS. For example, you could add the following rule to your stylesheet:

```css

div:empty {

display: none;

}

```

This will hide any div elements that are considered empty.

The Target Selector

Credit: youtube.com, Using the ":target" pseudo-class — CSS Tutorial

You can use the :target pseudo-class to target a unique element ID and the hash in the URL.

By using the # symbol and the element ID as an href attribute for your link, you can make the user "jump" to the targeted element.

The :target pseudo-class expands what you can do with anchors by letting you stylize the targeted element.

You can use the background: shorthand instead of background-color: to achieve the same result.

Anchors were always powerful and became even more so since the introduction of smooth-scrolling and scroll-padding-top.

You can now make things with native CSS that would have been quite a pain to do in JavaScript a few years ago.

Kevin Powell recreated the Netflix carousel with only CSS, showing just how deep you can go with anchor links and the target pseudo-class.

Intriguing read: Css Selector for Id

Frequently Asked Questions

What does :: do in CSS?

In CSS, double colons (::) are used to create pseudo-elements, which are used to style specific parts of an element, such as its first line or last child. They are part of the originating element and are used to target specific sections of an element's content.

What are the four pseudo-classes?

The four pseudo-classes are :link, :visited, :hover, and :active, which define different states of a link's appearance based on user interaction. Understanding these pseudo-classes is essential for styling links effectively in web development.

What is the difference between a pseudo class and a pseudo-element?

Pseudo-classes target an element's state, while pseudo-elements create a new, virtual element. Understanding the difference helps you write more precise and effective CSS code.

Ann Predovic

Lead Writer

Ann Predovic is a seasoned writer with a passion for crafting informative and engaging content. With a keen eye for detail and a knack for research, she has established herself as a go-to expert in various fields, including technology and software. Her writing career has taken her down a path of exploring complex topics, making them accessible to a broad audience.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.