CSS Attribute Selectors
CSS attribute selectors allow you to select HTML elements based on their attribute values. They provide a way to target specific elements that have certain attributes or attribute values. There are several types of attribute selectors in CSS:
- Attribute presence selector: Selects elements that have a specified attribute, regardless of its value. The syntax is
[attribute]
. For example,[required]
will select all elements that have therequired
attribute. - Attribute value selector: Selects elements that have a specific attribute value. The syntax is
[attribute=value]
. For example,[type="text"]
will select all elements that have the attributetype
with a value of"text"
. - Attribute substring value selector: Selects elements that have an attribute value containing a specific substring. The syntax is
[attribute*=value]
. For example,[href*="example"]
will select all elements that have an attributehref
containing the substring"example"
. - Attribute prefix value selector: Selects elements that have an attribute value starting with a specific prefix. The syntax is
[attribute^=value]
. For example,[class^="btn"]
will select all elements that have aclass
attribute starting with"btn"
. - Attribute suffix value selector: Selects elements that have an attribute value ending with a specific suffix. The syntax is
[attribute$=value]
. For example,[src$=".png"]
will select all elements that have asrc
attribute ending with".png"
. - Attribute exact value selector: Selects elements that have an attribute with an exact value. The syntax is
[attribute=value]
. For example,[target="_blank"]
will select all elements that have atarget
attribute with a value of"_blank"
. - Attribute space-separated value selector: Selects elements that have an attribute with a specific value in a space-separated list. The syntax is
[attribute~=value]
. For example,[class~="active"]
will select all elements that have aclass
attribute with"active"
as one of the space-separated values. - Attribute value starts with selector: Selects elements that have an attribute with a value that starts with a specific value, followed by a hyphen. The syntax is
[attribute|=value]
. For example,[lang|="en"]
will select all elements that have alang
attribute with a value that starts with"en"
followed by a hyphen.
These are some of the commonly used CSS attribute selectors. They provide powerful ways to target elements based on their attributes and attribute values, giving you more control over styling and behavior.