Design Development WebDesign

CSS tips and tricks #16 – CSS Atribute selector demistified

Last time we used practice to master CSS child selectors. After a great feedback from you, I decided to do the same thing with attribute selector as well. Personally, I found this selector and its variations more difficult to learn and master than child selectors. For those of you who are on the same side and want to get better in this topic, today is your lucky day. We are going to practice the attribute selector through code examples, so you can get immediate feedback and see the results.

To try out the code we are going to practice with you can either use your own text editor or tryout some of the free online solutions like Codepen, JSBin and Dabblet. You can work in all of them in HTML, CSS and JavaScript without the need to install anything.

HTML

At the beginning, let’s create some simple sandbox we can work with later on. Since we will practice attribute selectors, what element we use doesn’t really matter. For our needs we are going to use article element with lang attribute set to “en” containing h1 element with data attribute set to “data-heading”, rel set to heading external information” and three paragraphs of random text (I used Esperanto in this case) with data attribute set to “par-1”, “par-2” and “par-3” (par is abbreviation for paragraph) followed by two buttons with class set to “btn-green” (1st) and “btn-red” (2nd), type “button”, value of “Read more” (1st) and “Delete” (2nd). The text between opening and closing button tags value will be the same as value. Let’s also add data attribute to buttons with value of “data-btn-green” and “data-btn-red”.

HTML:

<article lang="en">
 <h1 data=”data-heading” rel=”external heading information”>End frazo posta popolnomo nk</h1>
 <p data=”data-par-1”>Uk jes oble laŭlonge, kuo pluen subjekta ki, tiom suprenstreko oni ec. Se nek eĥo land samideano. Gh hot kial sekve leterskribi. Iom ia miria pluso negativa, ant alii matematiko subtegmentejo si. Cit iomete pantalono suprenstreko go, timi kial sob ie. Ke sin geto mano naza, komo egalas ad sur.</p>
 <p data=”data-par-2”>To ipsilono oficiala sob. Deci malantaŭa be pro. Dek minimume centimetro difiniteco nv, avo ne giga denta, ro far manier antaŭmetado. End u hago patro internacia.</p>
 <p data=”data-par-3”>Dume foren enz iu. Ok giga naza longa jen, cii uj unua tempopunkto kromakcento. Emfazado supreniro ed mal, simil lasta eg tro. Sh for mono hoketo. Danke zepto poŭpo uk cia.</p>
 <button class="btn-green" type="button" data=”data-btn-green” value="Read more" role="button">Read more</button>
 <button class="btn-red" type="button" data=”data-btn-red” value="Delete" role="button">Delete</button>
</article>

With HTML set we can now focus on our goal – mastering attribute selector.

Basics

Let’s start with simplest form of the attribute selector that is using the name of element followed by square brackets containing certain attribute so we can target only elements containing this attribute. Let’s select the article via lang attribute and add padding of .25em to all sides. The syntax is element[attribute] {}. Since we are using the attribute itself and not its value, don’t use quotes in brackets.

CSS:

article[lang] { padding: .25em; }

Why not to change the font-weight of buttons to 700 (bold) by using role attribute? In order to select buttons, just change the element and attribute inside square brackets. Again, don’t use quotes in square brackets.

CSS:

button[role] { font-weight: 700; }

So, if you want to style some element through its attribute, you can use this simple form of attribute selector. However, keep in mind not to use quotes in these situations. Otherwise, your code will not work.

Equal

First variation of the attribute selector is the “equal to”. Its syntax is [attribute=”value”]. Yes, you can omit the element completely. This will select every element on the page containing the exact word specified in selector. For example, change the color of text inside article element to #333 through the value of lang selector. Since now, we are going to use quotes (like shown in the syntax) because we work with values. So, we will use lang for attribute and en for value.

CSS:

[lang=”en”] { color: #333; }

Now, change the background of “Delete” button through its data attribute value (“data-btn-red”).

CSS:

[data=”data-btn-red”] { background: #fa8072; }

Remember, this selector will apply the styles to element only when it will match exactly the attribute and value used in CSS.

Start with

Next is “starts with” selector. Its syntax is [attribute |= “value”]. This selector will select only elements its attribute starts with value specified in CSS or begin with specified value and is followed by “-”. Value has to be right on the beginning in order to work. For example, select all paragraphs targeting only elements whose data attribute starts with data-par keyword and change their color to #999.

CSS:

[data|=”data-par”] { color: #999; }

Begin with

A little modification to previous selector is “begin with”. There is a slight change in the syntax – [attribute^=”value”]. It works in similar fashion like “starts with”, but this one selects only elements which attribute specified in CSS is prefixed by that value. For example, we can select buttons via data attribute and using class beginning with “btn” to add border-radius of 3px and remove the border.

CSS:

[class^=”btn”] {
 border: 0;
 border-radius: 3px;
}

Contains

Next selector is “contains value”. It looks like [attribute*=”value”]. Every element with attribute containing specified value on some place will be selected. For example, let’s use it to change to font-family of first paragraph to Verdana, second to Arial and the third to Tahoma. All of them will also have sans-serif as fallback. To do that we will use data attribute and individual numbers included in this attribute (data-par-1, data-par-2 and data-par-3).

CSS:

[data*=”1”] { font-family: Verdana, “sans-serif”; }
[data*=”2”] { font-family: Arial, “sans-serif”; }
[data*=”3”] { font-family: Tahoma, “sans-serif”; }

Value in list

This selector works like the previous one except one thing. The value you use in CSS must be some word in list separated by white space. This is important. If the words will be separated by dashes it will not work. To see it in real life, let’s use it to center the heading. We will use rel attribute and heading as a value to select it and style it.

CSS:

[rel~=”heading”] { text-align: center; }

Remember, if there is no white space between words in the list (external-heading-information) styles will not be applied.

End with

The last variation of attribute selector is “end with”. The syntax is [attribute$=”value”]. Every element which attribute’s value ends with specified value (or is suffixed by it) will be selected. For example, let’s change the default background of “Read more” button and do the same with its hover and active states. To achieve this use data attribute and green suffix.

CSS:

[data$=”green”]{ background: #66cdaa; }
[data$=”green”]:hover{ background: #3cb371; }
[data$=”green”]:active { background: #2e8b57; }

Support

The support for these selectors is pretty decent. In case of IE 7 and 8 just make sure to specify !DOCTYPE.

Summary

We are done. I hope that this tutorial will help you understand these selectors in less time. I tried to make it as clear and simple as possible. However, feel free to contact if you will need any help or further explanation. AD

Anyway, if you have any questions, suggestions or ideas you want to share, leave a comment or contact me directly on twitter – AlexDevero – or facebook – lex.devero – or Google+ –+AlexDevero. Also, make sure to check out my website alexdevero.com.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.