Both pseudo-elements and pseudo-classes are defined by appending a specific keyword after the selector, following similar syntax rules, and setting corresponding styles in CSS rule blocks. Pseudo elements can add or replace content through the content attribute. For example, :before and :after can insert text, images, or other generated content. Pseudo-classes only affect the style of an element, but do not add or modify content. They change the behavior of elements based on user interaction, document structure, or other logical conditions. The main differences are as follows:
Target objects :
Pseudo-class selectors (Pseudo-classes) act on actual existing elements and are used to describe a specific status or relationship of the element, such as the access status of the link ( :visited
), the mouse hover status ( :hover
), and whether it is a document. the first child element in ( :first-child
), etc. They do not directly change the structure of the element, but affect how the element behaves under specific conditions. Pseudo-elements selectors are used to create and select a specific part within an element or to generate new, virtual content nodes before and after an element. For example, :before
and :after
can be used to insert additional content, :first-line
and :first-letter
select the first line of text and the first letter of the element respectively, :marker
controls the list item mark style, etc. These pseudo-elements do not correspond to actual elements in the HTML document, but styles can be applied to them as if they were real parts of the document.
Grammar identifier :
Pseudo-classes are usually identified by a colon :
:), such as :hover
, :focus
. Pseudo elements are identified in CSS3 by two consecutive colons ( ::
) to distinguish them from pseudo classes in older versions of CSS. Although most modern browsers still accept single colons to represent pseudo-elements (such as :before
), in order to comply with W3C standards and maintain best practices, it is recommended to use double colon forms, such as ::before
, ::after
.
Reusability :
Pseudo-classes can be combined in the same selector, such as a:hover:focus
to represent a link that is both hovered and focused. Pseudo elements generally cannot appear repeatedly in the same selector because they represent a specific part of the element or new content generated. An element can only have one :before
or :after
pseudo-element in effect at the same time.
CSS3 pseudo-elements are special CSS selectors that allow developers to add or modify the styles of specific parts of an element through CSS without modifying the HTML structure, or to generate and control virtual content inside or outside the element. The following is a detailed explanation and application examples of several common CSS3 pseudo-elements:
1. :before
and :after
:before
and :after
pseudo-elements each create a new, contentless, invisible "child element" after the selected element's content area. Then, by setting styles (such as content, size, color, background, etc.) to this pseudo-element, it becomes visible and visually appears as the part that immediately follows the content of the original element. These contents are defined by content
attribute, and additional styles can be applied.
grammar :
selector:before { content: "..." /* or other value */; /* Other style declarations */ } selector:after { content: "..." /* or other value */; /* Other style declarations */ }
Among them, the content
attribute is the key to defining the content generated by pseudo elements. It can accept the following values:
String : Directly specify the text to be displayed. HTML entities surrounded by quotation marks : such as content: "—";
(dash). URL : Insert image resources, such as content: url(image.png);
Generate content keywords : such as content: counter(name);
(counter) or content: attr(attribute-name);
(get element attribute value).
Application examples :
1.1. Add decorative content
Add quotes, icons, or other decorative elements.
Add quotes:
blockquote:before { content: open-quote; font-size: larger; color: #666; } blockquote:after { content: close-quote; }
Add custom icons before/after list items:
li:before { content: url(icon-checkmark.svg); margin-right: 0.5em; } li.completed:after { content: "2713"; /* Unicode character: check mark */ color: green; font-size: 1.5em; vertical-align: super; }
1.2. Clear float
:after
is often used to create an empty block-level element, and is used with clear:both
to clear the impact of floating on subsequent elements and avoid the "height collapse" problem.
.clearfix:after { content: ""; display: table; clear: both; }
Apply the .clearfix
class to container elements whose internal floats need to be cleared.
1.3. Replace or extend HTML content
Using the attr()
function, you can extract the value from the attribute of the element as the content of :after
to achieve dynamic text display.
abbr[title]:after { content: " (" attr(title) ")"; font-size: smaller; color: gray; }
In this example, when the mouse is hovered over the abbr
element with the title
attribute, a small gray bracket containing the value of title
attribute will be displayed.
1.4. Implement complex shapes and animations
Combined with content
, background
, border
and other properties as well as CSS3 transform
, transition
or animation
, you can use :after
to create complex shapes and animation effects.
.button:after { content: ""; display: inline-block; width: 0; height: 0; border-top: ⅓em solid transparent; border-right: ⅓em solid transparent; border-bottom: ⅓em solid #007BFF; border-left: ⅓em solid transparent; margin-left: 0.½em; } .button:hover:after { transform: translateY(-0.1em); transition: transform 0.2s ease-in-out; }
The above code creates a triangular drop-down arrow after the .button
element and implements a smooth downward animation on mouseover.
Things to note
:after
pseudo-element must be used with the content
attribute, otherwise it will have no effect. Since :after
is a created virtual element, DOM operations cannot be performed through JavaScript. Although the content generated by :after
can participate in layout, it is not included in the DOM, does not affect semantics, and does not affect accessibility functions such as keyboard navigation.
In summary, CSS3 pseudo-element selectors greatly enrich the expressiveness of web design by inserting custom content after element content without changing the HTML structure. Proficient use of pseudo elements and other CSS techniques can help developers build more beautiful, responsive and easy-to-maintain web interfaces.
2. :first-line
and :first-letter
The :first-line
pseudo-element selector is used to style the first line of text within the element, while the :first-letter
pseudo-element is used to style the first letter within the element.
grammar :
selector:first-line { /* Style declaration */ } selector:first-letter { /* Style declaration */ }
Application examples :
First line indent:
article p:first-line { text-indent: 2em; }
Capitalization and decoration:
article h2:first-letter { font-size: 2em; float: left; margin-right: 0.5em; line-height: 0.8; color: #8A2BE2; background-color: #F8F8FF; padding: 0.⅔em 0.⅓em; border-radius: 0.5em; }
The CSS3 pseudo-class selector is a powerful tool that allows developers to precisely position and apply styles based on the state of an element rather than its position in the document tree or inherent attributes such as class and ID. These selectors use special syntax structures to describe different conditional states of elements, such as user interaction, positional relationships, content characteristics, etc., thereby achieving dynamic and responsive web design. Below is a detailed explanation of CSS3 pseudo-class selectors and examples of their practical applications.
1. Static pseudo-class selector
:link
and :visited
:link
: Used to select hyperlinks ( <a>
elements) that have not been visited by the user. Typically used to set basic styles for unvisited links.
a:link { color: blue; text-decoration: none; }
:visited
: Select links that the user has visited. Used to set differentiated styles for visited links.
a:visited { color: purple; }
2. User interaction pseudo-class selectors :hover
, :focus
, :active
:hover
: Matches an element when the mouse pointer is hovering over it.
button:hover { background-color: #f0f0f0; cursor: pointer; }
:focus
: Select the element that receives focus, commonly found in form controls or focusable elements (such as <input>
, <textarea>
, <button>
, etc.).
input:focus { outline: 2px solid #007BFF; box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25); }
:active
: Used to indicate that the user is activating or pressing an element (usually on a mouse click or press on a touch screen).
a:active { color: red; font-weight: bold; }
3. Structured pseudo-class selectors :first-child
, :last-child
, :only-child
, :nth-child(n)
, etc.
:first-child
: Selects the element that is the first child of its parent element.
li:first-child { list-style-type: square; }
:last-child
: Selects the element that is the last child of its parent element.
div > p:last-child { margin-bottom: 0; }
:only-child
: Select elements that have no siblings.
.message:only-child { border-width: 2px; }
:nth-child(n)
: Select the nth child element of its parent element, where n
can be a number, keyword ( even
, odd
) or formula (such as 2n+1
).
li:nth-child(2n) { background-color: #f9f9f9; }
4. Content-related pseudo-class selectors
:empty
, :target
, :enabled
, :disabled
, :checked
, etc.
:empty
: Select elements without any content (including child elements, text nodes, etc.).
div.empty:empty { display: none; }
:target
: Select the element whose current URL fragment identifier (hash) matches the element ID.
#content:target { background-color: lightyellow; }
:enabled
and :disabled: Select the form elements in the enabled and disabled states respectively.
input:enabled { background-color: white; } input:disabled { opacity: 0.6; cursor: not-allowed; }
:checked
: Used when a check box ( <input type="checkbox">
), radio button ( <input type="radio">
) or <option>
element is selected.
input[type="checkbox"]:checked + label { text-decoration: line-through; }
5. Negate pseudo-class selectors
:not(selector)
:not()
: Selects elements that do not match the selector specified in parentheses.
/* Except all paragraphs with class "exclude" */ p:not(.exclude) { color: green; }
6. Other pseudo-class selectors
:root
, :nth-of-type(n)
, :nth-last-of-type(n)
, :first-of-type
, :last-of-type
, :only-of-type
etc.
:root
: Select the root element of the document (usually the <html>
element in HTML documents).
:root { --primary-color: #3498db; }
:nth-of-type(n)
and :nth-last-of-type(n): Similar to :nth-child(n)
, but only for child elements of a specific type among sibling elements.
article:nth-of-type(even) { background-color: #f5f5f5; }
:first-of-type
, :last-of-type
and :only-of-type: respectively select the first, last or only child element of a specific type among sibling elements.
div > p:first-of-type { font-weight: bold; }
By mastering the above CSS3 pseudo-class selectors and their application scenarios, developers can write more efficient, expressive and interactive CSS code to improve the user experience and visual effects of the website. As the CSS standard continues to evolve, more new pseudo-class selectors may join the ranks of CSS3 to provide richer and more sophisticated control methods for front-end development.
Whether it is a pseudo-class or a pseudo-element, they are all designed to enhance the functionality of CSS selectors, allowing developers to more finely control the style and layout of elements without changing the HTML structure.
This concludes this article about the differences, detailed explanations and application examples of CSS3 pseudo-elements and pseudo-class selectors. For more information about CSS3 pseudo-elements and pseudo-class selectors, please search previous articles on downcodes.com or continue browsing. Related articles below, I hope you will support downcodes.com in the future!