We launched a new IT training category! Check out the 140+ courses now.

Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Attribute selectors

From: CSS: Core Concepts

Video: Attribute selectors

Attribute selectors are one of my favorite selector types. They allow you to target elements based on the elements' attributes and the values of those attributes. While class and ID selectors allow styling based on a single attribute type, attribute selectors allow you to use any attribute you wish, and the syntax is flexible enough to allow you to target styling based on a number of different factors. So let's go ahead and take a look at this extremely powerful capability that CSS gives us. I have the attribute-selectors.htm open, and you can find this in the 02_12 folder.

Attribute selectors

Attribute selectors are one of my favorite selector types. They allow you to target elements based on the elements' attributes and the values of those attributes. While class and ID selectors allow styling based on a single attribute type, attribute selectors allow you to use any attribute you wish, and the syntax is flexible enough to allow you to target styling based on a number of different factors. So let's go ahead and take a look at this extremely powerful capability that CSS gives us. I have the attribute-selectors.htm open, and you can find this in the 02_12 folder.

Now I'm going to go over the structure of our page really quickly. It's a very, very small, short, little page, but there's a lot going on here that I want to talk about before we start targeting these elements. So we start off with an unordered list and inside that, we have individual list items which then contain links. Now it's the links that I want to really pay attention to. Notice the links all have href attributes, resource attributes, which tells the browser where it needs to go, or where the content that it's looking for is located at. And I also have a title attribute that adds to the accessibility of the links and basically describes what's going on with the links themselves.

Notice that one of them is an external link. It goes out to a site called lynda.com-- I think you've probably heard of it--and the title says visit lynda.com. The second one is a local link, so it would be linking in the same folder, and it's called about.htm, so it's just linking to another page, and the title of this one is visit about us. And then finally we have a link to a document. In this case, it would go into a directory called _docs/plan.pdf, and the title of this one is download our annual report. So maybe that's a link to an external resource that you might want people to download and use.

Now, below this unordered list, we have some paragraphs, and we have classes applied to those paragraphs. And if you've never seen this before, this is a way to apply multiple classes to an element. You just add whitespace between them and you can apply as many classes as you want. So our first paragraph has three classes applied to it: red, blue, and green; our second paragraph just has red and green; the third paragraph has red and blue applied to it; and then the fourth paragraph only has the class red applied to it. So class selectors, we've used those before.

We know what those can do for us, and we know that we could target those elements with class selectors, but we can't really filter or target them based on how many or which of those are applied to it. So we're going to see how attribute selectors can allow us to do that as well. So I'm going to go right up to my formatting, about line 26, where I'm going to start adding my attribute selectors. I'm just going to create a blank line there, and I'll just start off with the most basic attribute selector you can use, and that syntax merely targets the presence of an attribute, so let's see how we do that.

So I'm going to type in a, so I'm targeting all of our links, and then for the attribute you use brackets. So I'm just going to go ahead and do an opening and closing left and right bracket, and then inside those I'm going to type in the word title. So what this is going to do for me is it's going to go down to all of my links and it's going to look for which of them have a title attribute applied to it, and in this case they all have one applied. So then I'm going to go ahead and open up our curly brace, and inside that I'm going to do some very simple formatting here. I'm just going to type in color: red.

So I'm going to save that, and I'll preview it in one of my browsers, and I notice that all of the links go ahead and get that styling. The reason this happens is because every single one of them has this title. So if I were to change this one for just a moment and then go back and refresh, you can see that it loses that targeting, and it loses that targeting because it no longer has that title attribute. Okay, well I need that title attribute, so I'm going to undo that and save it again. Now that's the most basic attribute selector you can use, and it just basically looks for the attribute. If it finds it, it applies the styling.

It doesn't matter what the value is. Well, one of the really cool things about attribute selectors is that you can also check for specific values if you'd like. So I can get a lot more specific with this. I'm going to go right back into that selector and after title, I'm going to type in equals. Now, we'll just go ahead and target the one we deleted a second ago. In quotation marks, I'm going to type in visit lynda.com. Now it's really important that you type the case-sensitive spelling. Anything inside the quotation marks you have to get it exactly the same way it is on the page.

So if I save that, test it in my browser, I can see that now the styling only applies to the first link because it's the only one that has that explicit title attribute value. Now we can also further modify our attribute selectors to deal with not only the contents of an attribute, but match different patterns of that content as well. I'm going to just below this selector, and I'm going to start targeting our paragraph. So I'm going to type in p. Once again, I'm going to open and close one of those left and right brackets, and I'm just going to type in class="red," so nothing really new in terms of what we're doing here.

I'm going to go ahead and open up my curly braces, and I'm just going to apply the same styling, color: red. So I'll save this and refresh my browser, and I notice that only the last paragraph is targeted. Now you may have had this thought while looking at the code: hey! How is this different than a class selector? How is that different than just saying p.red? Well, it's not. It's exactly the same actually. So that's one of the interesting things about this. In many ways that's a lot like a class selector; however, it only targeted the last paragraph, and that's because this value must match exactly.

When I go down into my code, I can see that this is the only one indeed that just has red. Well, what if I wanted to target every single one of these that has the red class applied to it, even though these have multiple classes applied to it? How do I do that? Well, again, one of the nice things about attribute selectors is that they allow us to match patterns as well. So here is what I want you to do. Go right back up here and just before the equal sign, I want you to type in a tilde. Now if you've never used a tilde before, hold the Shift key down and just press the key, normally on left of the number one character, and that's your tilde.

So this ~=, this is a pattern matching, and it basically says go ahead and look for a whitespace-separated list that includes this word. So, it's specifically looking for those whitespace characters in between words, so it's looking for any instance of an attribute where multiple values might be used. So if I save this, go back into my browser and test it, now I see all of those paragraphs get that styling because each one of them has that red as one of the single values in the class attribute.

So again, the tilde allows us to go ahead and say, hey! Anytime this attribute, as well as any other attributes, are applied to it, go ahead and style it. Now there is other pattern matching that we can do as well. Let's revisit our link selector and kind of play around with those a little bit. I'm going to go back up to my link tag, and I'm going to change the title attribute to href, so now we're looking at the href attribute. And right before the equals sign I'm a type in a caret character. So, that caret character just above the six, this says go ahead and match any string that begins with a certain value. And in this case, I'm going to change visit lynda.com to http://.

So now what this is doing is it's saying, hey! Find any href attribute--which would be this-- that begins with this literal string. So in essence, this is a way to target any external link, because when you do an absolute link, you're going to be using http, more than likely. Of course, you could also group it with https if you're using external secured links. So if I go ahead and save this and refresh my browser, I can see that once again, the styling is only applied to the top link, because that is the only absolute or external link that we're using.

Now there is more matching that we can do here as well. The same way that this targets the beginning of a string, if instead of the caret, you used the dollar sign--and again, note that whenever we do these things there is no whitespace in here whatsoever. But when we use the dollar sign, instead of looking at the beginning of a string, we're looking at the end of the string. And in this case, I'm going to go ahead and change this to PDF. So now it would look through all your links and find any links that ended with PDF, which would be in this case resource links, and if I save that and test it, notice that again we are targeting the PDF download link.

In the last two cases we've done matching for the beginning of a literal string and the end of a literal string. What if you want to just test for the existence of a word within a literal string? Well, you can do that one as well. So if I highlight in this case and change my attribute to looking for title again and now instead of the care or the dollar sign I use the asterisk or the wildcard symbol, so it's title*= and I'm just going to type in in quotation marks the word visit. So now what that's going to do is it's going to look through any title attribute of the link and it's going to find any literal string that has the value visit inside of it.

And in this case we can see that these two links have visit inside of it, so we're anticipating that it will target those. So if I save this and test it, indeed it targets those first two links. Now it's not looking for that word visit in any one certain location in the literal string; it's looking for it anywhere. So if I go back into my code and I take the word visit and say please visit about us and save it, you can see the styling still works because the word visit is located somewhere within that title.

Now you might be wondering okay, what's the difference between this and this, because aren't both of them sort of matching that word wherever it's found? It is, but in the case of the tilde it's looking for that attribute value in a series of whitespace-separated attributes. For example, when you apply a class and use whitespace, it doesn't look at that as a literal string; it looks that as multiple values being applied. Whereas within the title this whitespace is just seen as part of a larger literal string. So the star, or the wildcard character, targets literal string values, whereas the tilde targets full attribute values that are just separated through whitespace.

It sounds like a minor difference, but it's really not. It actually a pretty large difference. Now you can use this to create all kinds of really cool formulas. For example, if I go back up to this title and change it to href, notice one of the things that I can do here is I can change visit to _docs, and that would look for any link that's looking for a resource within the docs folder. So that could be a Word document, a PDF, an Excel document, anything, it would all match. And if I save this and test it, I can see that indeed the styling is only applied to that particular resource.

So there's a lot that we can do with attribute selectors, and you've got all those different variations or formulations of the attribute selectors that allows you to target really, really specific instances, and you could do all sorts of really cool things. You could, for example, add an icon to all external links to let people know that clicking on them will take you outside of the site. You could add a PDF icon for every PDF that you're asking somebody to download, and they could sort of visualize which links are going to allow them to download a file. So there is all manner of things that you can do to it, and that's not even all of the different variations on attribute selectors.

It's really close. I think it's certainly enough to give you an idea of just how powerful these selectors are. Now support for attribute selectors isn't that great in some of the older browsers, especially when you get down to some of the substring matching versions; some of the really basic ones were supported a good while ago, but some of the substring matching ones, the support for them is still relatively new. So if you're going to use them, make sure you test your pages thoroughly in all the browsers that you're targeting before committing to them. I also recommend checking out the Selectors Level 3 Specification, which you can find here at w3.org/TR/selectors.

It has a whole section on attribute selectors. It's a great way to learn a little bit more about those pattern-matching attribute selectors that we have just covered, take a look at some of the ones that we didn't get to cover, and it's a great reference for you to use when you're writing these attribute selectors for your own sites.

Show transcript

This video is part of

Image for CSS: Core Concepts
CSS: Core Concepts

81 video lessons · 41823 viewers

James Williamson
Author

 
Expand all | Collapse all
  1. 4m 57s
    1. Welcome
      55s
    2. Using the exercise files
      4m 2s
  2. 1h 7m
    1. Exploring default styling
      4m 56s
    2. CSS authoring tools
      2m 29s
    3. CSS syntax
      4m 45s
    4. Writing a selector
      4m 10s
    5. Setting properties
      8m 40s
    6. Common units of measurement
      7m 47s
    7. Inline styles
      5m 1s
    8. Embedded styles
      5m 19s
    9. Using external style sheets
      10m 34s
    10. Checking for browser support
      8m 48s
    11. Dealing with browser inconsistencies
      5m 30s
  3. 2h 15m
    1. Structuring HTML correctly
      2m 51s
    2. Element selectors
      4m 52s
    3. Class selectors
      6m 4s
    4. ID selectors
      3m 27s
    5. Using classes and IDs
      10m 7s
    6. Element-specific selectors
      4m 35s
    7. The universal selector
      5m 42s
    8. Grouping selectors
      4m 49s
    9. Descendent selectors
      7m 32s
    10. Child selectors
      5m 7s
    11. Adjacent selectors
      5m 30s
    12. Attribute selectors
      12m 43s
    13. Pseudo-class selectors
      3m 54s
    14. Dynamic pseudo-class selectors
      8m 29s
    15. Structural pseudo-class selectors
      6m 45s
    16. Nth-child selectors
      13m 10s
    17. Pseudo-element selectors
      12m 40s
    18. Targeting page content: Lab
      8m 56s
    19. Targeting page content: Solution
      7m 59s
  4. 42m 39s
    1. What happens when styles conflict?
      4m 0s
    2. Understanding the cascade
      5m 47s
    3. Using inheritance
      6m 11s
    4. Selector specificity
      6m 55s
    5. The !important declaration
      4m 5s
    6. Reducing conflicts through planning
      3m 33s
    7. Resolving conflicts: Lab
      6m 45s
    8. Resolving conflicts: Solution
      5m 23s
  5. 1h 47m
    1. Setting a font family
      7m 10s
    2. Using @font-face
      9m 18s
    3. Setting font size
      7m 35s
    4. Font style and font weight
      6m 52s
    5. Transforming text
      3m 58s
    6. Using text variants
      2m 49s
    7. Text decoration options
      4m 26s
    8. Setting text color
      3m 2s
    9. Writing font shorthand notation
      8m 49s
    10. Controlling text alignment
      6m 33s
    11. Letter and word spacing
      9m 11s
    12. Indenting text
      4m 30s
    13. Adjusting paragraph line height
      10m 30s
    14. Controlling the space between elements
      6m 41s
    15. Basic text formatting: Lab
      8m 45s
    16. Basic text formatting: Solution
      7m 14s
  6. 2h 1m
    1. Understanding the box model
      16m 53s
    2. Controlling element spacing
      14m 29s
    3. Controlling interior spacing
      10m 49s
    4. Margin and padding shorthand notation
      6m 27s
    5. Adding borders
      8m 57s
    6. Defining element size
      10m 7s
    7. Creating rounded corners
      6m 58s
    8. Background properties
      2m 51s
    9. Using background images
      5m 10s
    10. Controlling image positioning
      10m 25s
    11. Using multiple backgrounds
      7m 5s
    12. Background shorthand notation
      5m 25s
    13. Styling container elements: Lab
      7m 55s
    14. Styling container elements: Solution
      8m 17s
  7. 47m 51s
    1. Color keyword definitions
      5m 4s
    2. Understanding hexadecimal notation
      6m 5s
    3. Using RGB values
      4m 58s
    4. Using HSL values
      5m 17s
    5. Working with opacity
      2m 23s
    6. Using RGBa and HSLa
      3m 8s
    7. Styling drop shadows
      5m 38s
    8. CSS gradients
      6m 32s
    9. Working with color: Lab
      4m 26s
    10. Working with color: Solution
      4m 20s
  8. 1m 58s
    1. Additional resources
      1m 58s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ .

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Join now Already a member? Log in

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed CSS: Core Concepts.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member ?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferences from the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.