


How do CSS selectors (e.g., class, ID, attribute, pseudo-class, pseudo-element) target HTML elements?
Jun 20, 2025 am 12:47 AMClass Selectors Target Elements with Specific Classes
<p> A class selector starts with a dot (.
) followed by the class name. It targets any element that has that class applied, regardless of what kind of element it is.
<p> For example:.highlight { background-color: yellow; }<p> This will apply a yellow background to any element with
class="highlight"
— like
, , or even
.<p> You can also combine class selectors with element types: p.highlight {
font-weight: bold;
}
<p> Now only <p>
elements with the class highlight
will be affected.- Multiple classes can be used on a single element.
- Avoid overly generic class names (like
.red
) unless you're sure about their usage. - Use meaningful class names related to content or function (eg,
.callout
, .nav-link
).
ID Selectors Are for Unique Elements
<p> An ID selector uses a hash symbol ( #
) followed by the ID name. Unlike classes, IDs must be unique within a page — there should only ever be one element with a given ID.<p> Example: #main-header {
color: darkblue;
}
<p> This will target the one element with id="main-header"
.- IDs have higher specification than classes, meaning they override class-based styles more easily.
- Because of this power, use IDs sparingly — especially if you're building reusable components.
- Great for targeting major layout areas like headers, footers, or primary navigation.
Attribute Selectors Match Based on HTML Attributes
<p> Attribute selectors allow you to target elements based on the presence or value of an attribute.<p> Basic syntax: input[type="text"] {
border: 1px solid #ccc;
}
<p> This applies to all <input>
elements where the type
is "text"
.<p> Other variations include:-
[attr]
– matches if the attribute exists at all -
[attr=value]
– exact match -
[attr~=value]
– matches a space-separated list (useful for classes) -
[attr|=value]
– matches hyphen-separated values ??(like language codes)
<p> These are handy when styling form elements or filtering links: a[href^="https://"] {
color: green;
}
Pseudo-classes Apply Styles Based on State or Position
<p> Pseudo-classes start with a colon ( :
) and represent a special state or position of an element.<p> Common examples:-
:hover
– when the user hovers over an element -
:active
– while the element is being activated (like clicking) -
:focus
– when the element has focus (often used for inputs) -
:nth-child()
– selects elements based on their position among siblings
<p> Examples: button:hover {
background-color: lightgray;
}
li:nth-child(odd) {
background-color: #f9f9f9;
}
<p> Some pseudo-classes like :link
and :visited
only work on anchor tags, so context matters.<p> Be careful not to overdo interactive states — keep accessibility in mind and test keyboard navigation too.
Pseudo-elements Modify Parts of Elements
<p> Pseudo-elements start with two colons ( ::
) and let you style parts of an element that aren't actual HTML nodes — like the first letter or line of text, or content before or after an element.<p> Common ones:-
::before
/ ::after
– insert generated content before or after the element's content -
::first-letter
– style the first letter of a block of text -
::placeholder
– style input placeholder text
<p> Example: p::first-line {
font-weight: bold;
}
<p> Or using generated content: .quote::before {
content: """;
}
.quote::after {
content: """;
}
<p> Keep in mind that pseudo-elements aren't real DOM elements — you can't select them with JavaScript or interact with them directly.
<p> Understanding how each type of selector works helps you write more precision, efficient, and maintainable CSS. You don't always need to reach for the most specific option — sometimes a class is enough. But knowing your options give you control when things get complex.
<p> Basically that's it.The above is the detailed content of How do CSS selectors (e.g., class, ID, attribute, pseudo-class, pseudo-element) target HTML elements?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to read excel data in html: 1. Use JavaScript library to read Excel data; 2. Use server-side programming language to read Excel data.

H5 page production refers to the creation of cross-platform compatible web pages using technologies such as HTML5, CSS3 and JavaScript. Its core lies in the browser's parsing code, rendering structure, style and interactive functions. Common technologies include animation effects, responsive design, and data interaction. To avoid errors, developers should be debugged; performance optimization and best practices include image format optimization, request reduction and code specifications, etc. to improve loading speed and code quality.

Ridge is a border style in CSS that is used to create a 3D border with an embossed effect, which is manifested as a raised ridge-like line.

Use the <br> tag in Dreamweaver to create line breaks, which can be inserted through the menu, shortcut keys or direct typing. Can be combined with CSS styles to create empty rows of specific heights. In some cases, it is more appropriate to use the <p> tag instead of the <br> tag because it automatically creates blank lines between paragraphs and applies style control.

H5 page production process: design: plan page layout, style and content; HTML structure construction: use HTML tags to build a page framework; CSS style writing: use CSS to control the appearance and layout of the page; JavaScript interaction implementation: write code to achieve page animation and interaction; Performance optimization: compress pictures, code and reduce HTTP requests to improve page loading speed.

How to view Bootstrap CSS: Using Browser Developer Tools (F12). Find the "Elements" or "Inspector" tab and find the Bootstrap component. View the CSS styles that the component applies in the Styles panel. Developer tools can be used to filter styles or debug code to gain insight into how it works. Proficient in developer tools and avoid detours.

Developer tools help you understand the rendering results of Bootstrap pages, including powerful features: the Elements panel provides HTML structure, real-time code modifications, and class name query. The Styles panel displays applied style rules, including priority and override relationships. The "Network" panel records network requests, analyzing performance bottlenecks and referenced versions.

In Angular app, how to change the color of the icon when the mouse is hovered over it? Many developers will encounter needs when building applications using Angular...
