How do attribute CSS Selectors work for href or data attributes?
Jun 29, 2025 am 01:11 AMAttribute selectors in HTML and CSS target elements based on their attributes. 1. Exact matches like a[] apply styles only when the attribute value is precisely as specified. 2. Partial matches using *= (contains), ^= (starts with), or $= (ends with) allow broader targeting such as dynamic URLs or file types. 3. Boolean attributes can be selected simply by presence, without needing a value, useful for UI states or flags. These selectors offer flexibility but require attention to syntax and specificity.
When working with HTML and CSS, attribute selectors are a powerful way to target elements based on their attributes — especially useful when dealing with links (href
) or custom data attributes (data-*
). These selectors let you style or manipulate elements without needing specific classes or IDs.

Matching Exact Attribute Values
One of the most straightforward uses of attribute selectors is matching exact values. This is especially handy for href
links or data-*
attributes where precision matters.

For example:
a[href="https://example.com"] { color: red; }
This rule applies only to anchor tags pointing exactly to https://example.com
. It won’t match if there’s a query string or fragment identifier added, like https://example.com?source=nav
.

The same logic works for data attributes:
div[data-role="button"] { cursor: pointer; }
This targets only those <div>
elements that have data-role="button"
and ignores similar ones like data-role="menu"
.
- Use this when you want strict control over which elements get styled.
- Keep in mind the match has to be exact — capitalization and extra characters matter.
Partial Matches with Attribute Selectors
Sometimes you don’t need an exact match. For cases like dynamic URLs or multiple data attribute variations, partial matches come in handy.
CSS offers several modifiers:
*=
(contains): matches any element whose attribute value contains the substring.^=
(starts with): matches if the attribute starts with the given value.$=
(ends with): matches if the attribute ends with the given value.
Here’s how they might look in practice:
a[href*="example"] { font-weight: bold; } a[href$=".pdf"] { background: url(pdf-icon.png) left center no-repeat; }
These are useful for:
- Styling all external links (e.g.,
href*="https://"
). - Identifying file-type links like PDFs or images.
- Targeting elements with shared but not identical data attributes.
Just remember that these can be less precise than exact matches, so test carefully.
Working with Boolean Attributes and Data Attributes
Some attributes don’t need a value to be selected — just their presence matters. This is common with boolean attributes like disabled
, but also sometimes seen with data-*
attributes used as flags.
For example:
button[disabled] { opacity: 0.5; }
Or with a data attribute:
div[data-active] { border: 2px solid green; }
This approach is great for:
- Indifferently checking whether something is present.
- Building UI states based on markup alone (like toggles or conditional styles).
You don’t need to write [data-active="true"]
unless you specifically want to match that value — just [data-active]
is enough to trigger the selector.
That’s basically how attribute selectors work with href
and data-*
attributes. They’re flexible, but small differences in syntax can make a big difference in behavior — so always double-check your conditions.
The above is the detailed content of How do attribute CSS Selectors work for href or data attributes?. 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

CSS blocks page rendering because browsers view inline and external CSS as key resources by default, especially with imported stylesheets, header large amounts of inline CSS, and unoptimized media query styles. 1. Extract critical CSS and embed it into HTML; 2. Delay loading non-critical CSS through JavaScript; 3. Use media attributes to optimize loading such as print styles; 4. Compress and merge CSS to reduce requests. It is recommended to use tools to extract key CSS, combine rel="preload" asynchronous loading, and use media delayed loading reasonably to avoid excessive splitting and complex script control.

In the following tutorial, I will show you how to create Lottie animations in Figma. We'll use two colorful designs to exmplify how you can animate in Figma, and then I'll show you how to go from Figma to Lottie animations. All you need is a free Fig

We put it to the test and it turns out Sass can replace JavaScript, at least when it comes to low-level logic and puzzle behavior. With nothing but maps, mixins, functions, and a whole lot of math, we managed to bring our Tangram puzzle to life, no J

ThebestapproachforCSSdependsontheproject'sspecificneeds.Forlargerprojects,externalCSSisbetterduetomaintainabilityandreusability;forsmallerprojectsorsingle-pageapplications,internalCSSmightbemoresuitable.It'scrucialtobalanceprojectsize,performanceneed

No,CSSdoesnothavetobeinlowercase.However,usinglowercaseisrecommendedfor:1)Consistencyandreadability,2)Avoidingerrorsinrelatedtechnologies,3)Potentialperformancebenefits,and4)Improvedcollaborationwithinteams.

CSSismostlycase-insensitive,butURLsandfontfamilynamesarecase-sensitive.1)Propertiesandvalueslikecolor:red;arenotcase-sensitive.2)URLsmustmatchtheserver'scase,e.g.,/images/Logo.png.3)Fontfamilynameslike'OpenSans'mustbeexact.

Autoprefixer is a tool that automatically adds vendor prefixes to CSS attributes based on the target browser scope. 1. It solves the problem of manually maintaining prefixes with errors; 2. Work through the PostCSS plug-in form, parse CSS, analyze attributes that need to be prefixed, and generate code according to configuration; 3. The usage steps include installing plug-ins, setting browserslist, and enabling them in the build process; 4. Notes include not manually adding prefixes, keeping configuration updates, prefixes not all attributes, and it is recommended to use them with the preprocessor.

CSScounterscanautomaticallynumbersectionsandlists.1)Usecounter-resettoinitialize,counter-incrementtoincrease,andcounter()orcounters()todisplayvalues.2)CombinewithJavaScriptfordynamiccontenttoensureaccurateupdates.
