robohash image acting as kam's profile photo

Tip 001 - Attribute Selectors


You can select things in CSS based on what attributes the element has:

[class] { /* Selects everything with the 'class' attribute -this use not recommended lol */
  color: red;

a[title] { /* Selects all anchors with a 'title' attribute */
  color: red;

div[data-my-thing="true"] { /* All divs with 'data-my-thing="true"' */
  color: red;

As in the example, you can select everything with an attribute, or even things where an attribute has a specific value.

That's already cool enough and all, but why stop there?

[title~="hello"] /* Where 'hello' is a word in the title, with spaces around it */
[title|="hello"] /* Where 'hello' is the whole title, or the beginning of the title */
[title^="hello"] /* Where the title starts with 'hello' */
[title$="hello"] /* Where the title ends with 'hello' */
[title*="hello"] /* Where the title contains 'hello' */

A good use case for a selector like this (there's a lot of them) is to change the styling of a link based on what the href says. In this example, the icons are different depending on the extension of the file being linked to, but you could also use CSS to add a "external link" indicator if the URL doesn't start with your own site.

See the Pen Extension-Based Link Styling by Kam Black (@kamblack) on CodePen.


Have you written a reply on another site? Put the URL here: