• Post category:CSS

CSS Attribute Selector with Example | Explained

CSS attribute selector example

This article is about CSS attribute selector with example.

Attribute selector []

An attribute selector is used to select HTML elements based on their attribute name and attribute value. We need to specify attribute selectors inside square brackets.

General Syntax of Attribute Selector

selector [attribute expression]
{
declaration list
}

Where:

  • A selector is optional, it can be a tag, class, id selector, etc…
  • Attribute expression can be a valid combination of attribute name, value, and associated operation.

Attribute selector with value

selector[attribute="value"]
{
declaration list;
}

It selects any HTML element, targeted by the selector, which contains an attribute name where the attribute value exactly matches the value specified in the attribute expression.

Attribute selector without value

selector[attribute]
{
declaration list;
}

It selects any HTML element, which contains an attribute name written in between the square brackets.

Example of attribute selector with value

CSS:

p[align="center"]
{
border:2px solid black;
background-color: cyan;
}

HTML:

<p>Paragraph Text 1</p>
<p align="center">Paragraph Text 2</p>

Output:

css multiple attribute selector

In the above code, CSS selects any paragraph element, which contains an attribute align, where the “align” attribute value exactly matches the value “center”. In HTML, all elements have the align attribute.

Example of attribute selector without value

CSS:

p[align]
{
border:2px solid black;
background-color: skyblue;
}

HTML:

<p align="right">Paragraph Text 1</p>
<p align ="center">Paragraph Text 2</p>

Output:

css multiple attribute selector

In the above code, CSS selects any paragraph element, which contains an “align” attribute.

Leave a Reply