CSS Selector [attribute]








The [attribute] selector selects elements with the specified attribute.

element1[attribute] is also called Simple Attribute Selector.

Simple Attribute Selector selects any element based on the presence of an attribute, regardless of the attribute's value.

Examples:

a[rel] {border-bottom: 3px  double   gray;}
p[class]  {border: 1px  dotted silver;}

Summary

CSS Version
2

CSS Syntax

[attribute] { 
   style properties 
}




Browser compatibility

[attribute] Yes 7.0 Yes Yes Yes

Example

An example showing how to use [attribute] CSS selector.

<!DOCTYPE html>
<html>
<head>
<style>
a[target]<!--from   w  w w.j  a va2 s  . co m-->
{
   background-color:red;
}
</style>
</head>
<body>
   <a href="http://java2s.com" target="_black">java2s.com</a>
</body>
</html>

Click to view the demo





Example 2

The following code uses the Element Attribute Selector.

<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
[href] {<!--   w  ww.  j  a v a  2s .  c  o m-->
  border: thin black solid;
  padding: 4px;
}
</style>
</head>
<body>
  <a id="anchor" class="class1 class2" href="http://java2s.com">
    Visit the website </a>
  <p>This is a test.</p>
  <a id="myAnchor" href="http://w3c.org">Visit the W3C website</a>
</body>
</html>

Click to view the demo

The code above used the attribute selector, which matches any element that has an href attribute, regardless of its value.