CSS3 Attribute Selector: Targeting the File Type

The attribute selectors is a really useful feature to select an element without adding superfluous id or classes. As long as the targeted element has an attribute like href, src and type we don’t have to do so.

The attribute selectors actually have been around since CSS 2.1, and now with a few more types of attribute selectors added in the CSS3 specifications, we are able to target the element’s attribute even more specifically.

And, in this post, we are going to use one of the syntax to select the file type that is inserted as part of the attribute’s value.

The Syntax and Browser Support

The file type is always at the end of the file name. So, to select that file type we can use the following syntax [attr$=”value”]. This syntax uses the $= operator that will target the end of the attribute value, for example:

a[href$=".pdf"]:before {
  background: url('../images/document-pdf-text.png') no-repeat;

The snippet above will select every link that the attribute value ends with .pdfand insert a word-document-icon in the :before pseudo-element.

While this is a common utilization of this selector, we surely can go beyond that.

The Example

You’ll never know, if you never try. We just need to try something new to get a better understanding of something we don’t understand yet. So here, we are going to demonstrate how this syntax can be very helpful and handy to target an element in a particular HTML structure that used to be a bit difficult to apply using only plain CSS.

Below, we have an HTML5 structure to list three images with its caption. It is only for demonstration purpose, your markup doesn’t have to be exactly like the following snippet (e.g. you may have only one image or even three more images), but the point is you get to know how this syntax can be applied in a particular HTML structure.

Read Full Article

By www.hongkiat.com

Leave a Reply

Your email address will not be published.