CSS Attribute Selectors | Definition of Attribute selectors in CSS | Syntax & Example Program with Attribute Selectors

In CSS, to target elements with certain attributes, there is a possibility by using attribute selectors. The CSS [attribute] selector matches elements on the basis of the presence or value of a given attribute. Let’s get complete knowledge on attribute selectors on CSS by going through these quick links available below.

Attribute selectors in CSS

CSS Attribute Selector is a specific type of selector that is applied to select the HTML elements with a specific attribute and/or attribute(s) value that are associated with it.

An attribute selector can be made by putting the attribute — (not obligatory) with a value — within the square brackets ([….]). Let’s check the syntax of CSS Attribute Selectors from the below section.


The following syntax is classified on the basis of an attribute or attribute value while styling a specific HTML element:


Attribute presence selectors

One of the first attribute selectors is Attribute presence selectors. By using this attribute selector in CSS, we will check if an element has an attribute using the square brackets[]syntax.

p[key] will select all p (paragraph) tags in the page that have an key attribute, regardless of its value of the content:

p[key] {
  /* ... */

Do Read:

Exact attribute value selectors

We can check for an attribute value using the =, then the CSS will only be applied to the attribute matching the exact content:

p[key="my-key"] {
  /* ... */

Match an attribute value portion

There are some operators that are used to match an attribute value portion like as follows:

  • = it checks for the exact value, and other operators are listed under
  • *= notes if the attribute contains the partial
  • ^= notes if the attribute starts with the partial
  • $= checks if the attribute ends with the partial
  • |= checks if the attribute starts with the partial and it’s followed by a dash (common in classes, for example), or just contains the partial
  • ~= checks if the partial is contained in the attribute, but separated by spaces from the rest

If we add anisimply before the closing bracket, the check will be case insensitive. Otherwise, all the checks above are case-sensitive.

Styling Forms with Attribute Selectors

The attribute selectors are especially helpful for styling forms without class or id. For example, let’s look at the below code:

input[type="text"], input[type="password"] {
    width: 150px;
    display: block;
    margin-bottom: 10px;
    background: yellow;
input[type="submit"] {
    padding: 2px 10px;
    border: 1px solid #804040;
    background: #ff8040;


CSS Attribute Selectors example output