Attr Selectors in CSS Language
CSS (Cascading Style Sheets) is a powerful language that allows web developers to style and format HTML documents. While most developer
s are familiar with basic CSS selectors like classes, IDs, and element types, there are more advanced selectors available for targeting specific elements on a webpage. One of these advanced selector types is the “Attribute Selector.”Attribute selectors are incredibly useful when you need to target HTML elements based on their attributes or attribute values. They provide flexibility and can help you style or manipulate elements that don’t have a specific class or ID. In this post, we’ll explore attribute selectors in CSS with examples to illustrate their practical use.
Basic Attribute Selector
The basic attribute selector allows you to target HTML elements with a specific attribute. It follows this format: [attribute]
.
Example:
/* Select all anchor tags with a 'target' attribute */
a[target] {
color: blue;
}
In this example, all anchor (<a>
) tags with a target
attribute will have their text color set to blue.
Attribute Selector with Value
You can get even more specific by targeting elements with a particular attribute value. This is done with the format [attribute=value]
.
Example:
/* Select all input fields with a 'type' attribute set to 'text' */
input[type="text"] {
border: 1px solid #ccc;
}
In this example, all input fields with the attribute type
set to “text” will have a 1px solid gray border.
Attribute Selector with Partial Value
Sometimes you may want to target elements with attributes containing a specific value within a larger attribute value. You can do this with the “substring match” attribute selectors.
Example:
/* Select all image tags with a 'src' attribute containing 'logo' */
img[src*="logo"] {
border: 2px solid red;
}
This will apply a red border to all images whose src
attribute contains the word “logo.”
Attribute Selector with Prefix Value
You can also target elements with attributes that start with a specific value. This is done with the “prefix match” attribute selectors.
Example:
/* Select all links with an 'href' attribute starting with 'https' */
a[href^="https"] {
font-weight: bold;
}
This CSS rule makes all links whose href
attribute begins with “https” bold.
Attribute Selector with Suffix Value
Similar to prefix matching, you can target elements with attributes ending with a specific value using the “suffix match” attribute selector.
Example:
/* Select all files with a 'href' attribute ending in '.pdf' */
a[href$=".pdf"] {
color: #ff0000;
}
In this case, all links with an href
attribute ending in “.pdf” will have their text color set to red.
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.