CSS3 selectors you should know as your pockets, part one
Digging into CSS3, this article exposes few new selectors, priceless resource to keep our CSS clean, while still keeping a precise control on the HMTL.
Looking for ways to optimize your CSS? This article may help. Selectors and pseudo classes are in fact what makes a Cascade Style Sheet effective, linking it to the various elements in the HTML. Being quite vast argument, this is the first part. You can read the second part on CSS3 Selectors You Must Know as Your Pockets, part two, that will be online in few days.
Let’s dig in
As support, you can view examples of what we’ve seen along the article in the demo page, or download it as file.
Keeping it simple and straight to the point, CSS3 gives us a tighter control upon the HTML and its rendering, while keeping everything neat. Let’s dig in, starting from the most obvious ones.
1. *
This’s the most generic selector we can use. It’s like a Jolly, it selects everything, and it should not be used lightly, since it’s high demanding on the rendering of the browser.
* { opacity: 0.9; }
Nevertheless the * selector (star symbol), it’s priceless for debugging and development. In the example above, I set up all the elements in page with an opacity of the 90%, making all of them slightly transparent. This way I can see through and keep an eye on what’s happening under. I use it also to fix alignment on grid.
2. #X
The id selector is very specific. It should not be duplicated since the id selector has the purpose to identify an unique specific element. This way you can target that element, and only that, with high specificity. Take note that having two elements with the same id on the same page invalidates your HTML.
#header { background-color: #eee; }
We should use an id when we’re sure we need to target one unique element. If we need to style more at the same time, we better use a class.
3. .X
A class is set up in the CSS with a comma preceding the name.
.meta { font-style: italic; }
This way, all the elements (may they be div, p, span…) with a class set up as .meta, will be styled in italic. Note that an id has a higher specificity than a class. Let’s assume we have the following HTML.
<div id="my-id" class="my-class">Lorem Ipsum</div>
And the following CSS.
#my-id { font-size: 24px; }
.my-class ( font-size: 12px; }
The font encapsulated in the div will be rendered at 24px, even if we may think that the second rule should override the former. Also, you can set up several classes at the same time in your HTML, just spacing them with nothing more than… ehr… a space.
<h3 class="meta error message alignleft">Read carefully!</h3>
4. Tag or Type
Often we don’t need classes or ids at all. We can add more precise instructions later on. For instance, when I style my typography I set up the basic styles, and I fix them where necessary. In my design it may well be that all the ul (unordered list) should have an indent, or that the p should have their own line-height.
p { line-height: 20px; }
ul { margin-left: 10px; }
You can also list more tags or types at one time, and assign them the same set of instructions.
ul, li, .meta { color: #333; }
5. X Y
A descendant is simply an element that is inside an other. For instance, it’s common to target a li after its ul, and a li after an ol (ordered list), to distinguish the two cases. Lining more descendants one after the other increases the specificity of the instruction, but it’s not a good practice going too far. The syntax below should be, in fact, avoided.
body #header ul li a span {
color: #900;
}
Rarely it’s necessary to define so strictly what should happen inside a span, that’s inside an anchor, in an unordered list, within the element with the id #header, among the body. Keep your styling lighter as possible, targeting the element with a touch. It will be much easier later to fix modify or just manage your styles.
6. X > Y
This is a parental selector, it targets an element inside an other, but only if the former is the direct parent of the latter. For instance.
ul#menu > li { font-size: 18px; color: olive; }
ul > li { font-size: 14px; color: teal; }
Will affect only the li element that are direct child of the ul with the id #menu. And not any sub levels. Then, with the second line, we target only the grand children, since the first rule has a higher specificity. To clarify, let’s analyze the html below.
<ul id="menu">
<li>Child 1</li>
<ul>
<li>Grand-child 1</li>
<li>Grand-child 2</li>
</ul>
<li>Child 2</li>
<li>Child 3</li>
</ul>
Our rule instructs the first line of li with a determined font-size: 18px, and a color: olive, while the second line of li, the grand childrens, will not be affected. Then we apply to all the li following an ul different settings (font-size: 14px, color: teal), but the first rule keeps a tighter control on the all the li that follow an ul with the id #menu. Still not clear? Download the example page and play around a bit.
7. X + Y
Adjacent selection, similar to the parental selector, but in this case we’re selecting the element that comes right after the former element in the statement. Let’s see in practice. First the HTML.
<div id="header"></div> <div id="main-pic"> <img src="images/pic-1.jpg" /> </div> <div id="other-pic"> <img src="images/pic-2.jpg" /> </div>
Then its CSS.
#header + div { width: 100%; }
Our rule, #header + div { width: 100%; }, selects specifically the block immediately following the element with the id #header. The second div, identified as #other-pic, is unaffected.
8. X ~ Y
Sibling selector, it’s more loosey than the previous, letting us to select each element of the type Y that follow an element of type X.
#header ~ div { border-bottom: 1px solid #aaa; }
Considering the HTML we used few line above, we’re now selecting also the second div, giving it a bottom border. In other words, we’re selecting each div that follows an element with the id #header.
9. :link :visited :hover :focus :active
We move now on the first pseudo classes, commonly used to style links and inputs. Pseudo classes are used to style elements by their status or content. It will more clear styling an anchor.
- a:link
Selects an anchor with a url specified in its properties - a:visited
Selects an anchor linked to a resource we’ve already visited - a:hover
Selects the anchor when we move the mouse on it - input:focus
Selected when we focus on the element - input:active
Selected when we’re interacting with the element
A short explanation may be useful. Most of the browsers let us select every element with pseudo classes, with famous distinctions (who said Internet Explorer?) for which we should pay attention. But basically, the five pseudo classes above are very efficient combined with anchors and inputs. I choose an input for the last two, ‘cos it makes more sense, but usually I style anchors the way below.
a:link, a:visited { color: blue; }
a:hover, a:focus, a:active { color: red; }
With the rules above a link will be blue, even if it has been visited before. And on mouse hover, or if selected with the keyboard (some browsers allow for such a navigation), it will become red. For input fields, you may wish to play with something like the rules below.
input { background-color: #ddd; }
input:focus { background-color: #fff; }
Where the input has a gray background. It changes to white once we’re interact with it. A pretty way to style an input where the user is supposed to digit some text.
10. X[title]
Known as attribute selector, this syntax selects an element on the HTML that has a particular attribute. In the example below we’re giving a border to every img that have a title.
img[title] { border: 1px solid #900; }
Below, we’re targeting the link to a specific URL assigning to them a colored background. All different links will be unaffected.
a[href="http://carlorizzante.com/"] { background-color: lime; }
The property just written is very specific. If the link would have a href of http://carlorizzante.com instead of http://carlorizzante.com/, it wouldn’t be affected. We can be more elastic.
a[href*="carlorizzante.com"] { background-color: lime; }
Here we’re targeting links with carlorizzante.com as part of the URL, might it be http://carlorizzante.com/, www.carlorizzante.com/about/ and so on. It just needs to have the value expressed in the statement as part of the value of the whole attribute. This way we’re still targeting the link below.
<a href="http://carlorizzante.com/portfolio/">I'm a Link, too</a>
Attribute selectors open a door to quite an alchemy.
11. Playing around with attribute selectors
With a little bit of craft, we can have fun targeting almost everything we may wish. Let’s see some examples.
- a[target]
it accounts for anchors with a target attribute - a[target="_blank"]
it selects only anchors that have the specific value of _blank as target (here, only links that open in a new windows) - img[title*="flower"]
only images with a title that contains the substring “flower” - img[title~="flower"]
only images with a title that contains the word “flower” will be affected, “flowers” for instance will be not - p[lang|=en]
selects paragraphs with a lang attribute value starting with en - a[src^="https"]
links whose src attribute value begins with https - a[src$=".pdf"]
only links whose src attribute value ends with .pdf
As an application of what we’ve just seen, we can set rules for the links to download the supported types of image.
a[src$=".jpg"],
a[src$=".png"],
a[src$=".gif"],
a[src$=".pdf"] {
color: green;
}
Or we could set up our own attribute, targeting precisely what we need to. Not an uncommon practice.
First the HTML.
<a href="http://carlorizzante.com/images/image-1.jpg" ><img metadata="download image" src="images/pic-1.jpg" /></a>
And this is the CSS.
img[metadata~="image"] {
padding: 10px;
border: 3px double #900;
}
img[metadata~="download"] {
background-color: gray;
}
The rules target img with the custom attribute metadata named metadata. And only if it contains the words image or download. If it contains the word download we apply a background. If it contains the word image we apply a border. Quite simple, it shouldn’t be difficult to create your own solution.
12. Playing with :checked and more
I’ve recently learnt a nice trick, which can be used to attract attention on input elements, like checkboxs, radio buttons, or even textfields. Get inspired by the following css, and try to find the key of the problem. It isn’t immediate but playing around can be source of gratification. First the CSS.
input[type="checkbox"]:checked + label { background-color: fuchsia; }
input[value] { background-color: fuchsia; }
And the HTML.
<p><input type="checkbox" name="option1" id="option1" checked /><label for="option"> Checkbox 1</label></p> <p><input type="checkbox" name="option2" id="option2" /><label for="option"> Checkbox 2</label></p> <p><label for="first">Empty textfield: </label><input type="textfield" name="textfield1" id="textfield1" /></p> <p><label for="first">Populated textfield: </label><input type="textfield" name="textfield2" id="textfield2" value="Lorem Ipsum" /></p>
Just as a remind, examples of what we’ve just seen are visible at CSS3 Selectors You Must Know as Your Pockets, test page, or download as file.
Similar Resources
CSS3 Selectors You Must Know as Your Pockets, part two
5 CSS3 Properties You Need to Master about Background, Corners and Shadows
Articles on similar topics
- Keep your CSS in order, for your own good
- WordPress, save your client from the danger nested in the Dashboard
- Showing the grid while developing using the CSS property opacity
- 5 CSS3 properties you need to master about Background, Corners and Shadows
- How to use the clearfix method with LESS for a higher HTML flexibility
