CSS :target Selector

Joe Maddalone
InstructorJoe Maddalone
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 5 years ago

The :target selector allows us to interact with a fragment identifier, or hash, in our URL from CSS.

[00:00] The target pseudo-selector allows us to interact with fragment identifiers in our URL with CSS. So to illustrate this, I'm going to go ahead and set up a few divs that are going to have an ID of tab followed by an integer. They're also going to have a class of tab, and inside that they're going to have an H1, and its innerHTML is going to be tab integer content. So we're going to go ahead and set up three of those, save that, and we can see on the right here we've got our three tabs.

[00:31] I'm going to go ahead and save that here in our style, a tab has a color of green. Save that. Everything's working as it should. Now we're going to say a tab that is the target, using the target pseudo-selector is a color of red. Save that, everything's going to stay the same, but up here in our address bar I'm going to add a #tab1, and you see tab1 has become red, because it is the target as identified in the our URL. If I switched tab2, tab2 becomes red, and tab3, tab3 becomes red.

[01:11] Now to illustrate this a little bit further I'm going to create a handful of anchor tags here. It's going to have an HREF equal to # tab integer, and its innerTEXT is going to be tab integer, and again we'll create three of those to match our tabs. Now when I click on tab1, tab1 becomes red, tab2, tab2 becomes red, tab3, tab3 becomes red. Just to take this a little bit further on our class of tab, I'm going to say display none.

[01:41] Our class of tab that is the target, I'm going to say display block, and now we go to tab1 it becomes visible, tab2 becomes visible, tab3 becomes visible.

egghead
egghead
~ 6 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today