CSS Rules and Selectors
Now let's get to CSS, and we'll start, perhaps, with decoding the abbreviation. CSS stands for Cascading Style Sheets, but:
-- Why is it called "cascading"? -- this is a question I often ask candidates during interviews. The answer is an analogy, and it's a pretty good one: imagine a cascade of waterfalls, and you're standing on one of the steps holding an inkwell, pouring its contents into the water -- all the water below will be colored by the ink. Same with CSS: if you set a style at a certain level, it flows down the "cascade" to the web page elements, coloring them with the "ink" of your style.
-- Why do I need all this? -- when working with jQuery, you need to be able to read CSS rules fluently and compose CSS selectors to find the elements you need on the page. Practically every task you'll solve with jQuery starts with finding the right element on the page, so knowing CSS selectors is mandatory.
But let's take it step by step. Here's a simple example of quite semantic HTML:
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="UTF-8"/>
<title>Page Title</title>
<link rel="shortcut icon" href="/favicon.ico"/>
<style>
body {
font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
font-size: 14px;
}
h1, h2, h3 {
color: #333333;
}
header, section, footer {
position: relative;
max-width: 800px;
margin: 16px auto;
}
article {
padding: 16px;
margin-bottom: 16px;
}
#content {
padding-bottom: 16px;
}
.box {
border:1px solid #ccc;
border-radius:4px;
box-shadow:0 0 2px #ccc;
}
</style>
</head>
<body>
<header>
<h1>Page Title</h1>
<p>Page Description</p>
</header>
<section id="content">
<h2>Section Title</h2>
<article class="box">
<h3>Article Title</h3>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing...</p>
</article>
<article class="box">
<h3>Article Title</h3>
<p>Morbi malesuada, ante at feugiat tincidunt...</p>
</article>
</section>
<footer>
© jQuery for beginners
</footer>
</body>
</html>This is an example of simple and proper HTML with a bit of CSS sprinkled in. Let's break down the selectors in the CSS code above (I intentionally kept the CSS inline rather than in a separate file, because it's more visual this way):
body-- these rules will be applied to the<body>tag and all its descendants; remember: font settings cascade down through the element hierarchyh1,h2,h3-- we're selecting<h1>,<h2>and<h3>tags and setting the font color for these tags and their descendants#content-- we're selecting the element withid="content"; padding settings don't cascade to descendants, they only change for this specific element.box-- we're selecting elements withclass="box"and modifying the border appearance of elements with that class
Now in more detail, with more advanced examples:
h1
finding elements by tag name
#container
finding an element by identifier id=container (identifiers are unique, meaning there should be only one on the page)
div#container
finding a <div> with identifier container, but the previous selector is faster, while this one has higher specificity
.news
selecting elements by class name class="news"
div.news
all <div> elements with class news
#wrap .post
finding all elements with class="post" inside the element with id="wrap"
.cls1.cls2
selecting elements with two classes class="cls1 cls2"
h1, h2, .posts
listing selectors -- we'll select everything listed
.post > h2
selecting <h2> elements that are direct children of the element with class "post"
a + span
all <span> elements immediately following an <a> element will be selected
a[href^=https]
all <a> elements whose href attribute starts with https will be selected (presumably, all external links)
This is by no means the full list; a description of all CSS selectors can be found on the corresponding W3C page: https://www.w3.org/TR/selectors-3/
Going back to our waterfall analogy, imagine that on the next step someone pours ink of a different color. In real life, we'd get a mix of colors. But in CSS, this change will "repaint the water" on all subsequent steps, because in CSS what matters is order -- order and priorities. Let's get to the point:
the first step of our cascade has the lowest priority -- these are the browser's default styles
no matter what browser vendors claim, these styles can differ across browsers, which is why there's still such a thing as CSS Reset -- a great equalizer
on the second step are styles set by the user deep in the browser settings; rarely seen in practice
the most important for us -- the page author's styles, but even here everything follows an order
the lowest priority goes to styles linked as a file
<link rel="stylesheet" type="text/css" href="...">or embedded inside HTML with the<style>tag:and naturally, when priorities are equal, the last one declared wins
then come the ones that bad people hardcoded (not you, you won't do this) in
style="":and then the
!importantflag shows up and breaks everything, because a rule with this flag becomes more important than even inline styles, turning everything upside down:to override such a style, the only option left is to write inline styles with the
!importantflag:
the
!importantadventure isn't over yet -- if there are user styles with this flag, now it's their turnand even browsers use
!important, and such styles have practically the highest priority
If your head isn't hurting yet, I'll also mention that when calculating whose rules take precedence, the specificity of selectors is analyzed, and here's how the math works:
the calculation uses three weight positions --
[0:0:0]for each element identifier (
#id) --[1:0:0]for each class (
.class) or pseudo-class (:pseudo) --[0:1:0]for each tag (
<a>,<div>, etc.) --[0:0:1]where
[1:0:0]>[0:x:y]>[0:0:x]when the score is tied -- again, the last one declared wins
Here are selectors arranged by ascending priority (the corresponding HTML code will follow):
a tag has the lowest priority
[0:0:1]
p { color: orange }
adding class intro to the tag
[0:1:1]
p.intro { color: green }
adding another tag
[0:1:2]
article p.intro { color: blue }
... we need more classes
[0:2:2]
article.news p.intro { color: red }
the identifier id="pinned" on its own outweighs all tags and classes combined
[1:0:0]
#pinned { color: darkblue }
adding the <p> tag, and specificity increases
[1:0:1]
p#pinned { color: darkcyan }
adding another identifier id="top"
[2:0:1]
#top p#pinned { color: darkgreen }
using style overrides any rules from external files and stylesheets
¯_(ツ)_/¯
<p style="color:#333">...</p>
There are also specificity calculation rules related to certain pseudo-selectors like :not() and :where(). The pseudo-selector itself doesn't add weight to specificity, but the rule inside the parentheses does:
Yeah, calculating specificity can genuinely become a non-trivial task, so here are a couple of calculators for you to choose from:
Homework
Here's a piece of CSS for practice -- write the corresponding HTML for it (this is an interview question ;):
And one more:
Last updated