A selector is a key element of CSS. Everyone uses CSS selectors in their project's CSS knowingly or unknowingly.
To reset CSS we use:
- * { padding: 0; margin: 0;}
Here * is a selector that targets all elements. We use .classname or #idname that are also selectors that refers to an element with a specified classname or idname.
Attribute selectors
Using an Attribute selector we can easily target a specific element in our page without having Classes or IDs.
1. element[attr]: Selects an element having a specific attribute.
Example
In the above example, the font color green will be applied to all a tags having the name attribute.
2. element[attr=value]: Helps to select an element having a specified attribute and value.
Example
- a[name="nav"]{
-
- color: #00F;
-
- }
In the above example, the font color #00F will be applied to the a tag having the attribute name=”nav”.
3. element[attr~=value]: Helps to target an element having a word or space separated word in an attribute value.
Example:
- a[name~="left"] {
-
- color: #0F0;
-
- }
In the above example, the color #0F0 will be applied to the a tag having the word “left” in the value. It can have name=”left”, name=”primary left” or name=”left top”. It will not apply to name=”lefttext” or name=”left-bottom”.
4. element[attr |= value]: Targets an element having a specified attribute starting with the specified value.
Example
- a[name|="right"] {
-
- color: #f40;
-
- }
In the preceding example, color will be applied to the a tag having the name attribute that has a value starting with “right”. It considers name=”right-nav” but it won't consider name=”righttext” or name=”right_nav”.
5. element[attr^=value]: Refers to an element having a specified attribute starting with a specified value. It works in a similar way as the | selector, the only difference is that it considers an entire word without space.
Example
- a[name^="text"] {
-
- color: #600;
-
- }
In the preceding example, font color will be applied to a tag having a specified attribute value starting with nav. It can have name=”text1” or name=”text-top” or name=”text_Content”.
6. element[attr $= value]: Selects an element whose attribute value ends with a specified value.
Example
- a[name$="bottom"] {
-
- color: #0FF;
-
- }
In this example, the color blue will be applied to a tag having an attribute value ending with “bottom”. It can have values like “text-bottom”, “text_bottom” or “bottom” but it won't work for “bottom-text”.
7. element[attr *= value]: Selects an element having a specified attribute value. The value does not need to be an entire word, it also considers part of a word.
Example
- a[name*="cont"] {
-
- color: #930;
-
- }
In this example, the color yellow will be applied to a tag having an attribute value that contains the word “left”. It consider values like name=”content”, name=”text_cont” or name=”continue”.
Conclusion
In my future article we will discuss more CSS3 features. Always feel free to share your suggestions or comments.