Last week we began looking at some of the selectors we have available for hooking css styles into our html. We briefly touched on some simple selectors and mainly focused on attribute selectors.
This week I want to continue and talk specifically about combinators before starting to cover pseudo class selectors.
Note: As a reminder the numbers in parenthesis after the combinator or pseudo-class are the version of css they were introduced in.
Combinators
Combinators, as the name suggests, are ways to combine several different selectors into new and more specific selectors.
There are 4 types of combinators targeting parent/child and sibling relationships between elements.
Descendant combinator E F (1) — matches an element F that’s a descendant of an element E. Note that descendant combinators target all descendants and not just direct children.
{code type=html}
- List Item 1
- List Item 2
- List Item 2-1
- List Item 2-2
- List Item 3
{/code}
{code type=css}
ul li {background: red;}
{/code}
All 5 list items will be styled with a red background as each is a descendent (either child or grandchild) of the unordered list.
Child combinator E > F (2) — matches an element F that’s a child of an element E. The difference here is that F must be a direct child of E.
{code type=html}
- List Item 1
- List Item 2
- List Item 2-1
- List Item 2-2
- List Item 3
{/code}
{code type=css}
ul>li {background: red;}
{/code}
Only list items 1, 2 and 3 above will be styled with a red background. Both are children of the ul, while list items 2-1, and 2-2 are grandchildren.
Adjacent sibling combinator E + F (2) — matches an element F immediately preceded by an element E. Note the word adjacent. Only the first element F after E will be targeted.
{code type=html}
Heading
Paragraph 1
Paragraph 2
Paragraph 3
{/code}
{code type=css}
h1+p {font-size: 1.5em;}
{/code}
Only paragraph 1 will be styled with the increased font-size as it’s the only paragraph adjacent to the h1.
General sibling combinator E ~ F (3) — matches an element F preceded by an element E. Unlike the above this will match any sibling and not just the first.
{code type=html}
Heading
Paragraph 1
Paragraph 2
Paragraph 3
{/code}
{code type=css}
h1~p {font-size: 1.5em;}
{/code}
Here all three paragraphs will have the increased font-size as all are preceded by the h1. It isn’t necessary for the elements to be adjacent in the general sibling combinator.
Beyond Simple Selectors
Note that you aren’t limited to only using simple elemental selectors in combinators. Any selector, including attribute selectors can sit on either side of the combinator.
{code type=css}
ul a[title]
li#first>a[rel=”external”]
h1+p.intro
h2.myclass~p[class=”intro”]
{/code}
All of the above are valid combinators.
Pseudo-Class Selectors
There are a variety of pseudo-class selectors, one group of which, I’m sure you use often. Others you may have seen and even used before and some will probably be new to you.
The W3C divides pseudo-classes into the following groups:
- dynamic pseudo-classes
- target pseudo-class
- language pseudo-class
- UI element pseudo-class
- negation pseudo-class
- structural pseudo-classes
We’ll cover the first 5 above today and then pick up next week with structural pseudo-classes and another group of selectors, pseudo elements.
Dynamic Pseudo-Classes
This is the group I’m sure you’re familiar with. It consists of the link and user action pseudo-classes and should look instantly familiar.
link pseudo-classes (1)
E:link — matches an element E that’s the source anchor of a hyperlink of which the target is not yet visited.
E:visited — matches an element E that’s the source anchor of a hyperlink of which the target has already been visited.
user action pseudo-classes (1) and (2)
These match an element E during certain user actions
E:active — When the link is active (in the process of being clicked).
E:hover — When the visitor hovers over the link.
E:focus — When the link has active focus.
I’ll assume you know all of the above well enough that little explanation is necessary.
One tip when using :link, :visited, :hover, and :active on a single element is that they need to come in that order. Remember the expression LoVeHAte.
Target pseudo-class (3)
If you’ve ever created a named anchor by adding a # to a url then you’ve created a target pseudo-class in your html.
E:target — matches an element E that’s the target (named anchor) of the referring url.
{code type=css}
span:target {background: yellow;}
{/code}
The above would place a yellow background behind the span.
These are good to use to help quickly orient people who’ve clicked to a specific part of a page from another page or from somewhere else on the same page.
Lang pseudo-class (2)
E:lang(fr) — matches an element of type E in the language specified (here “fr” or French)
{code type=html}
Je suis français.
{/code}
{code type=css}
p:lang(fr) {color: red;}
{/code}
I’m not sure how often you use multiple languages on a single page, but if you do here’s a way to target specific text in a different language.
UI element states pseudo-classes (3)
A common trick to improve form usability is adding constraints like enabling and disabling form items based on what the visitor has already filled out.
Note that by default html elements are neither enabled nor disabled. A scripting language like Javascript is typically used to enable or disable the elements, however you could manually set html attributes on the inputs.
E:enabled — matches a user interface element E which is enabled.
E:disabled — matches a user interface element E which is disabled.
E:checked — matches a user interface element E which is checked (radio-button or checkbox).
{code type=html}
{/code}
{code type=css}
:enabled {color: green;}
:disabled {color: red;}
:checked {background: yellow;}
{/code}
Here red and green are used to let visitors quickly determine which form elements are currently available. Checked items are given a yellow background so they stand out as having been checked.
Presumably we’d use Javascript to change the enabled and disabled attributes based on which method is chosen as preferred.
Negation pseudo-class (3)
The negation pseudo-class does what you might expect. Adding it selects everything other than the selector being negated.
E:not(S) — matches an E element that does not match simple selector S.
{code type=html}
{/code}
{code type=css}
div:not(.two) {color: orange;}
{/code}
The above styles all the text in the first and third divs to be orange, since these two divs do not have a class of two assigned. The negation selector looks simple enough, but it can get quite complex in a hurry.
You’ll likely be able to find other ways to target the elements you want rather than use the negation selector, however one negation might be able to replace quite a few other selectors and may be more appropriate to use at times.
Browser Support
Support for combinators is good once you get past IE6. It’s not quite as good for pseudo-classes (outside of the dynamic pseudo-classes, which have good support) where we’re generally looking at IE9 and up for support.
You can check the links below to see the support for any of the specific selectors.
Summary
As was the case with attribute selectors I’m guessing you’ve used some of these combinators and pseudo-classes before. I’m also guessing most of what’s here you don’t use. That’s certainly true for me.
Outside of the generic descendant combinator and the dynamic pseudo-classes, I can’t say many of these ever find their way into my code. Some like :lang probably won’t come up that often, but hopefully you can see the benefit of the UI element states, the negation selector, and the other combinators.
Next week I’ll wrap up this quick walk through of selectors. We’ll look at the last of the pseudo-classes, the structural pseudo-classes and then look at pseudo-elements. Both will apply to some very practical ways we’re likely to want to style our pages.
Download a free sample from my book, Design Fundamentals.
Very nice and helpful article Steven. I really like to use pseudo classes and don’t wanna miss them any more. If you use them (for example :before & :after)you can reduce the HTML code. That’s the way to more semantic and faster coder and …
Thanks. It would be nice if pseudo classes had more support, but some do. By the way :before and :after are pseudo elements and I have a post coming on those on Monday.
I am bit confused over child combinations. I am not getting the actual concept behind it, as you mention in this article that child combinations matches an element B if that element is a direct child of element A…
i.e – ( A > B)
For example :
HTML :
Unordered Lists
Unordered Lists
Unordered Lists
Ordered List
Ordered List
Unordered Lists
CSS :
ul > li {
color: red;
}
Then according to you Unordered Lists item should be selected and the text color should be red in color.
But when i am trying this code on my pages the desired output is not coming. Instead hole list item is getting selected. Making all the list item red in colors. Plz clear my doubts.
I’m not 100% sure I’m following what’s happening. Is there a page online somewhere I could see?
ul > li {
color: red
}
should make all list items that are direct children of an unordered list red. Is that what you’re saying is happening?
If the page is online post a link or email it to me so I can take a look.
Thanks for your reply Steven….
Actually i am testing this code offline on my system.
Follow this – link http://pastie.org/9396907
In this link i have written the code which i am not getting according to you child combinators select those element which are direct child. If B is an children or direct child of A then B gets selected right.
i.e. (A > B)
But when i am trying this code then whole list are getting selected and making it red in colors.
You can follow the link so that u can understand what actually i am trying to say .
(Note – sorry for my bad English i am little bit passive in it )
No need to apologize for your English. You speak English better than I speak any language outside of English. You also speak it better than quite a few people who call English their native language.
Thanks for the link. I see what you mean about the code. I see how all the list items, even the ones nested inside the ordered list are red.
I think what’s happening is since the ordered list is inside a list item that should be red, everything inside it also becomes red through inheritance.
If you add
ol {color: blue}
to your css, you’ll see the list items in the unordered list are red and those in the ordered list are blue.
Then if you change ul > li to ul li, without the > you can see the difference between using > and not using it.
Thanks for your reply and thanks for appreciating my English. Now i got the real concept behind this child combinators
I am a quiet frequent visitor of your site and this is the first time i am replying to you. I never expected that you will reply so fast to my doubts, this feels great and amazing keep it up. Bye the way this website serves a great knowledge regarding web designing. And usually before searching on google most of the time i prefer your site for reference.
Thanks for this amazing knowledge sharing website.
If you don’t mind i am gonna ask you one personal doubt. Actually i have been doing webdesign for past few years may be 2 or 3 and half years but still i feel i am not that much confident in it some time back i designed some layout which was great for me but still when i see these modern days website or new designing concept i feel lacking in confidence. I know i have to learn a lot before achieving this but i am not getting a proper path on how to proceed further in web designing and development although i have read some of your article and that about section it feels great but still i want a proper path so that i can follow. I hope you can understand me what i am trying to say. So i want you to put up an detailed article or some thing like that so that i can get some idea and follow a particular path.
About me – i am a self taught web designer who learn almost everything from internet and presently i am pursuing a degree on computer science.
@ string1301 – Guess I wasn’t as quick to reply this time. My bad.
Thanks for the compliments about the site.
Don’t compare yourself to others. It sets you up to feel less confident, because you’re always choosing someone else’s best work against your own. Only compare yourself to yourself. Do you do better work today than 2-3 years ago. My guess is you do. Just keep trying to improve and in a few years look back and compare what you can do to what you can do now.
Try also to look at your work and identify what you do well and what needs improvement. Then do your best to learn what you want to learn to improve.
If you don’t mind waiting a little bit, I’ll see what I can come up with for an article. It’s something I write about so why not one more article. Is there anything specific you’d want me to cover in the article? What have you done so far to learn design and development? Why do you think you’re not on a proper path?
Thanks.
Again thanks for your reply steven.
You are right i should never compare my self with others. As i know i am the best competitor for my self. And definitely i am gonna consider your words.
And about my learning technique i never followed any general or any study material to learn web designing. I am a self learner and most of the things i learned from internet, but first i started to learn web designing using web builder software but at that point i realize that web builder softwares or any IDE like Dreamweaver will not help me to learn these things in better way. So then i started to learn html and after some time i just switched my self to CSS and at that point i was actually not knowing what CSS is i just studied some code from different website and also from some online tutorials like w3schools.com and i just applied it on my works but later on i found out some more bit of CSS so i just started to learn these things like CSS inheritance, document tree, and when i started to learn more and more i found out that there are things like CSS3 and other stuffs at this point i realize that what i have learn is not an organised one so i feel lack of confident. So i just want you to help me to organize my study and work. As i know there are things like Designing patterns or Designing approach which i want to learn basically we can say that i want to go through some theory on web designing.
As my writing is not organized but i know you will get what i am actually trying to say
Once again thanks in advance
I’ll see what I can come up with. I actually have a post about learning in general that will publish in a few days, though it’s probably not quite what you were looking for.
I don’t think I could give you an exact course to follow, because there’s no one path to learning web design and development. What I can do is offer some thoughts about what I think everyone should learn. It would list the higher level general topics and offer suggestions about which subtopics you might want to then learn.
Again I’ll see what I can come up with.
Thanks Steven 😀