Mind Diary

CSS Selectors

“CSS selectors” let us assign a single CSS rule to a specific HTML element which enables us to selectively style individual elements while ignoring others.

It is how we say things like “I want this paragraph to be blue and that other paragraph to be yellow.”

Class Selectors:

“Class selectors” let us apply CSS styles to a specific HTML element. They let us differentiate between HTML elements of the "same type", like when we have five <p> elements, for example, but we want to style only one of them.

Class selectors require two things:

  • A class attribute on the HTML element in question.
  • A matching CSS class selector in your stylesheet.

Thus, if we want to style only one of our paragraphs differently than the rest of them, we can use a class selector to do this. This could be, for instance, the synopsis of a newspaper article.

We first, in our HTML file, add a class attribute to the desired paragraph, like this:

<p class="synopsis">CSS selectors let you select individual HTML elements in an HTML document. This is super useful.</p> Using a class selector to style a paragraph

Then, in our CSS file, we can style that <p class="synopsis"> element as follows:

.synopsis {
   color: #7e8184;
   font–style: italic;
}

This rule is applied only to elements with the corresponding class attribute. Notice the dot (.) prefixing the class name.

Class Naming Conventions:

The value of the class attribute can be (almost) anything we want as long as it matches the selector in our CSS stylesheet. The standard naming convention for classes is to use all lowercase and hyphens (or underscores) for spaces, just like file and folder names.

Adding a class attribute does not alter the semantic meaning of our HTML document at all — it is purely for hooking into our CSS stylesheet.

It is better to avoid naming classes based on their "appearance". For example, if we chose the name "italic" for our class attribute, it would only be confusing.
Using something semantic like "synopsis" gives us more freedom for our CSS to customize how that synopsis is displayed.

More Useful Divs:

The class attribute can be defined on any HTML element, so that our generic <div> and <span> boxes become much more useful. We can use them to style both individual elements as well as arbitrary sections of our web page.

Container Divs:

A <div> tag does not alter the semantic structure of a page, which makes it a great tool for defining the "presentational structure" of a web page.

By wrapping other HTML elements in <div> tags, we can "organize" our site into larger layout–oriented chunks without messing up how search engines view our content.

Container divs - what people see and what the robots of search engines see

Thus, we can, for example, create a "fixed–width" layout using the "auto–margin" technique.

First, we wrap our entire document in a generic <div> and give it a unique class, like this:

<body>
   <div class="page">
      <!–– Content goes here ––>
   </div>
</body>

Then, we add the following to our CSS stylesheet:

.page {
   width: 600px;
   margin: 0 auto;
}

No matter how we would "resize" our web browser window, our web page will always be 600 pixels wide and centred in the available space.

As we can use the "auto–margin" technique to centre any HTML element, we can also use it to centre "multiple elements" at the same time by nesting them in a generic container <div>.

This is how layouts are defined in more complex web pages. For instance, if our page had a sidebar, we would nest all the sidebar elements in another <div> with a "sidebar" class.

Without using class selectors to "differentiate" our <div> elements, none of this would be possible.

Reusing Class Styles:

The same class can be applied to multiple elements in a single HTML document. This means that we can now "reuse" arbitrary CSS declarations wherever we want.

Organizing similar graphical elements into "reusable CSS rules" makes life much easier as a web developer. Thus, if we have three or four elements with the same class attribute, and we wanted to, say, change the background colour of any of them, we would only have to do it in "one place" and all our corresponding elements would automatically update.

Reusing CSS rules

Modifying Class Styles:

What if we have two elements with the same class attribute and we want to alter only the second one a little bit ?
Fortunately, we can apply multiple classes to the same HTML element, too. The styles from each class will be applied to the element, giving us the opportunity to both reuse styles of a certain class and override some of them with a new class, like this, for example:

<div class="button">Button One</div>
<div class="button call_to_action">Button Two</div>

The element that has "two" classes can be styled using either of them, so that the styles shared by both buttons can live in the "button" class, while the styles specific to the second button reside in the "call_to_action" class.

Notice how multiple classes are separated by "space" inside the same class attribute.

Order Matters:

When we have an element with "two" classes, the styles applied to the second class overrides those which are applied to the first one. Such overriding occurs because of the order of both "call_to_action and _button_ in our CSS stylesheet.

When there are two conflicting properties in a CSS file, the last one is always the one that gets applied. So, if we would move .call_to_action to the top of our stylesheet, the .button would have the final word on the styles applied to that element.

While the order of the class attribute in our HTML element has no effect on override behavior, the precedence is determined solely by the “order” of the CSS rules in our stylesheet.

Descendant Selectors:

Descendant selectors

Descendant selectors let us target only those elements that are "inside" of another element.
For example, we can specifically target an <em> element that is inside a paragraph with a class attribute called "synopsis" using the following code:

.synopsis em {
   font–style: normal;
}

Descendant selectors are not limited to class selectors — we can combine any other group of selectors this way. They are a great tool for applying styles to exactly the element you want.

Do NOT Overdo It:

Although you can nest descendant selectors as deep as you want, do not get carried away. Life gets confusing and terrible when you start writing rules that look like this:

/* Try to avoid this */

.article h2 .subheading em {
   /* Special styles */
}

Pseudo–Classes for Links:

In a rendered web page there is more going on than just our HTML content. There is “stateful” information about what the user is doing (as opposed to the content we have authored).

The classic example thereof is a "link". As a web developer, you create an <a href> element. After the browser renders it, the user can interact with that link. They can "hover" over it, "click" it, and visit the URL.

Pseudo-classes

At any given time, an <a href> element can be in a number of different states, and we can use pseudo–classes to style each one of these states individually.
We can think of such states as class selectors that are built into the web browser.

Basic Link Styles:

Pseudo–classes begin with a colon followed by the name of the desired class. The most common link pseudo–classes are as follows:

  • :link  –  A link the user has never visited.
  • :visited  –  A link the user has visited before.
  • :hover  –  A link with the user's mouse over it.
  • :active  –  A link that is being pressed down by a mouse (or finger).

We can style these four "states" of a link as follows:

a:link {
   color: blue;
   text–decoration: none;
}
a:visited {
   color: purple;
}
a:hover {
   color: aqua;
   text–decoration: underline;
}
a:active {
   color: red;
}

Visited Hover State:

Our a:hover style is applied to both "visited" and "unvisited" links. We can refine our links even more by stringing pseudo–classes together, like this:

a:visited:hover {
   color: orange;
}

Thus, while hovering over a still "unvisited" link changes it to aqua, hovering over a "visited" link will turn it orange as we have just created a dedicated hover style for "visited" links when we added the above–mentioned CSS rule to our stylesheet.

However, due to some complicated CSS internals, this last CSS rule breaks our a:active style — when we click down our link, it will not turn red anymore !

Visited Active State:

We can fix our a:visited:active state by adding the following to the "end" of our CSS stylesheet.
Note that the order in which these various states of our link are defined in our CSS stylesheet matters:

a:visited:active {
   color: red;
}

Pseudo–Classes for Buttons:

Pseudo–classes are not just for styling links — they can be applied to any kind of selectors.

Pseudo–Classes for Structure:

There is a bunch of other pseudo–classes that provide extra information about an element's surroundings.

For example, the :first–of–type and the :last–of–type pseudo–classes select the "first" and the "final" elements of a particular type of elements within their parent element.
This gives us an alternative for selecting specific elements.

Thus, if we have, for example, five paragraph elements, and we wanted to add some space only after the last one, we could use the :last–of–type pseudo–class in order to specifically target the last paragraph element, like this:

p:last–of–type {
   margin–bottom: 50px;
}

ID Selectors:

“ID selectors” are a more strict alternative to class selectors. They work pretty much the same way, except we can only have one element with the same ID per page, which means we cannot reuse styles at all.

The corresponding CSS selector must begin with a hash sign (#) opposed to a dot.

The problem with using id is that if we wanted to "share" this style with another button, we would have to give it another unique id attribute.

ID selectors are generally frowned upon. Use class selectors instead.

URL Fragments:

id attributes need to be unique because they serve as the target for “URL fragments”.
Fragments are how you point the user to a "specific" part of a web page. They look like an ID selector stuck on the end of a URL.

Pointing the user to a specific part of a web page by using the id attribute

CSS Specificity:

CSS rules are applied from top–to–bottom. This allows us to override rules in a predictable manner.

CSS rules are applied form top to bottom

Unfortunately, not all CSS selectors are created equal. “CSS specificity” is the weight given to different categories of selectors. This means that certain selectors will always "override" other ones, regardless of where they appear in the stylesheet.

ID selectors have higher specificity than class selectors. The whole “order matters” concept only works when all your rules have the same specificity.

CSS rules are not necessarily applied in sequential order, and this can get very confusing. However, you should try to make the web browser apply your CSS rules in sequential order by writing CSS that uses the same specificity.

Summary:

  • With all this interplay between CSS and HTML, it can be hard to know where to start building a new web page.
  • You need content before you can "present" it, so your first step is usually to mark up your raw content with HTML tags.
  • Once that content is prepared, you are ready to style your elements one by one.
  • When you discover a need for some extra structure to create a desired layout (e.g., turn a group of elements into a sidebar), that's when you start wrapping your content in container <div>'s.