[CSS] Selectors (4) – Attributes

You can select elements with the attribute values. Note that the attribute selection is case-sensitive.

 

1. Attribute Selectors in CSS2

CSS2 provides the basic selectors with attributes. Attribute selectors are placed in the brackets ([ ]).

  • [attribute] : if a target attribute exists
  • [attribute=value] : with an exact match
  • [attribute~=value] : if an attribute contains a specified word
  • [lang|=value] : language attribute selector; starting with the value – use :lang() instead
<input type="text" class="txt" value="Hello World" />
<input type="button" class="btn" value="Click" />
<input type="checkbox" class="chk" />/Check it
<input type="email" class="mail" required />
<input type="tel" class="txt" value="123-4567" />

Note that “~=” selector is good for checking which class is defined.

input[required] { border: 1px solid red; } /* email */
input[type="button"] { border: 1px solid blue; } /* button */
input[class~="txt"] { border: 1px solid green; } /* text, tel */

 

2.  Attribute Selectors in CSS3

CSS3 adds new attribute selectors based on the regular expressions.

  • [attribute^=value] : begins with the value
  • [attribute$=value] : ends with the value
  • [attribute*=value] :  contains the value
<input type="text" value="A: Hello World." />
<input type="text" value="B: Hello Universe." />
<input type="text" value="C: Good morning." />
<input type="text" value="D: Good bye." />

*=” is more universal than “~=“. “~=” only works in a word-level (space-separated).

input[value^="A:"] { border: 1px solid green; } /* A */
input[value$="Universe."] { border: 1px solid blue; } /* B */
input[value*="Good"] { border: 1px solid red; } /* C, D */

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s