Selectors

Selectors are, as you can guess, ways to select elements. These selectors apply to both CSS and JavaScript later on.

By name

The first way to select a group of elements is to select them by name. An example use in CSS would be this:

p {
    /* some styling */
}

Here, the styling will be applied to all <p> elements in the html file. This works with any valid html tag, and the general syntax is:

tagName {
    /* styling goes here */
}

By class

The next way is to select elements by class. As mentioned before, elements in the same class would be expected to have similar styling and behaviour, so it makes sense that you would want to select a class of elements instead of by name. An example is as follows:

.long-div {
    /* some styling */
}

Here, the styling will be applied to all elements that have the class "long-div". Note that to specify that a class is being selected, you need to prefix the class name with a dot (.)

.class-name {
    /* styling goes here */
}

By id

Lastly, you may want to select an element by its id. This involves using the # symbol as a prefix to the id name:

#useless-button {
    /* some styling */
}

In this case, the element with the id "useless-button" will be assigned the styling. Generally:

#id-name {
    /* styling goes here */
}

Multiple elements

If multiple elements of different classes/tags are being assigned the same styling, it is possible to combine them using commas:

a, p, div {
    /* some styling */
}

Here, the same styling is being assigned to the <a> tag, the <p> tag and the <div> tag. This reduces the length of the file and makes it easier to control shared styling.

If I wanted to add a few unique rules to the <div> elements while keeping the rest of the styles constant, I could do this:

a, p, div {
    /* common styles */
}

div {
    /* extra styling only for div */
}

This is because styles are cascading (hence Cascading StyleSheets). This means that if style rules for an element are defined multiple times, all the properties are combined and applied to the element.

If the same property is redefined multiple times, then the last definition of the property is applied.

Redefining properties

When the same property is redefined for a group of elements, the browser decides which definition of the property to use based on this simple algorithm:

  • Check the selector and choose the most specific selector's property: id selectors are most specifc, and tag name selectors are the least specific

  • If there are multiple most-specific selectors, then pick the one that appears last and before the element appears (a style rule that appears after the element will not be applied to the element)

Next steps

Next we'll look at colors in CSS and what values they can take on.

Last updated