Lesson 93 – Complete 2020 Web Development Bootcamp

Lesson 93 – Combining CSS Selectors

You can combine multiple selectors and then apply CSS to all of them. For example:

h1, h2, h3, h4, h5, h6 {
  color: red;
}

Hierarchical selectors target an element that is inside of another element –

#title .container-fluid {
  padding-top: 3%;
  text-align: left;
}

The above example selects the element with the class “container-fluid” which is inside the element with the id of “title”. It will not select an element with the class “container-fluid” which is outside of the element with the id “title”.

When using hierarchical selectors you must leave a space between the two selectors.

You can also use combined selectors. When using combined selectors, there is no space between the two selectors. For example,

h1#title {
  color: red;
}

When using hierarchical selectors you read the selectors from right to left. When using combined selectors, you read the selectors from left to right.

Lesson 91 – CSS Selector Priority

If you select the same value twice in the same element then the last value will be applied. For example:

h1 {
  color:red;
  color: green;
}

In this example the color of the h1 element will be green and not red.

If you have an h1 element with a class of “container” and the following CSS code, the h1 element with the class of “container” will have the color of yellow and not red. This is because a class is more specific than an h1 element.

h1 {
  color: red;
}
.container {
  color: yellow;
}

If in the same example as given above (an h1 element with the class of “container”), the h1 element also has a title of “heading” then the following CSS would apply the color blue to the h1 element. This is because the title “heading” is more specific than both a class and an h1 element.

h1 {
  color: red;
}
.container {
  color: yellow;
}

#heading {
  color: blue;
}

To avoid creating conflicting CSS rules, you should:

  • Use ID’s very sparingly – don’t use ID’s when you can use a Class;
  • Apply only one class to an element – not multiple classes to the same element;
  • Avoid using inline styles in your HTML code.