Decoding CSS: Mastering Cascade, Selectors, and Specificity for Smarter Styling.
Tags: css, cssselectors, specificity, cascade
Published: 2024-04-18 22:50:52

In the ever-evolving world of web development, mastering CSS (Cascading Style Sheets) is crucial for creating visually appealing and technically sound websites. At the heart of CSS lie three fundamental concepts: the cascade, selectors, and specificity, and understanding these concepts is key to writing efficient and effective style sheets. This article delves deep into these concepts, explaining each one with clarity and providing examples.

## CSS SYNTAX
Generally, a syntax is a set of rules that define what the various combinations of symbols mean. In computer science, a syntax is essentially a set of keywords and characters that a computer can read, interpret, and convert into tasks that it knows it needs to do.
They are like recipes which have to be followed to get the desired result. If a particular step in the recipe is missed, the meal wouldn’t turn out as it should, this is the exact same thing when an incorrect syntax is used in CSS and even programming languages in general.

A computer program is a set of instructions written in a programming language that tells the computer what to do. Like humans, computers cannot get a sense of what instructions you are passing across if the instruction is not given in its entirety. The closest thing you can get to this are Integrated Development Environments that can point out where an error is from, but even with this, you still have to write the correct syntax. A coding syntax must be exact and specific if not, there will be errors.

To understand the CSS syntax, let us learn about CSS rulesets first. The structure of CSS rule set is

```
P {
Color:red
}
```
The above is known as a ruleset. Where `P` is the selector, `color` is the rule property and `red` the property value. `Color:red` is referred to as a declaration.
CSS rulesets are the fundamental building block of stylesheets. This means a stylesheet contains lots and lots of rulesets.

### The syntax of a CSS rule set

1. Each rule set must be wrapped in curly braces.
2. A colon should be used to separate a property from its value.
3. A semicolon is used to separate one property declaration from the next.
4. Multiple selectors are separated by commas.

## SELECTORS
CSS selectors are patterns used to select and style HTML elements. In the ruleset example given earlier, it is seen that CSS rules are usually added to selectors to specify the styling of the _selected_ element. CSS selectors go hand in hand with **CSS combinators** which are symbols that specify the relationship between selectors. 

CSS selectors allow elements to be targeted based on their type, class, id, attributes among others WHILE combinators allow elements to be targeted based on their position in relation to other ones. CSS combinators gives more precision in selecting an element(s). There are different types of selectors and combinators that have been made available by CSS.

### Types of selectors
<u>Element or type selector</u> - target HTML elements by their type. 
In this example, the h1 element selector is used in the CSS rule. This rule will style all `h1` elements on the page.

```
<h1>Element Selector</h1>
<p>Targets HTML elements by their element type (tag name)</p>
<h1>Id Selector</h1>
```
```
h1 {
    color: greenyellow;
}
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7z61objftl2mcxogspo1.png)

<u>Id selector</u> - Targets a unique HTML element by its assigned ID.

```
<h1>Element Selector</h1>
<p>Targets HTML elements by their element type (tag name)</p>

<h1>Id Selector</h1>
<p id="text">Targets HTML elements by their Id</p>
<p>This paragraph won't be affected by the ID selector</p>
```
```
h1 {
    color: greenyellow;
}
#text {
    color: red;
}
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8ixwg0ajbnzuy0nhzfsu.png)

<u>Class selector</u> - Targets HTML elements by their assigned class
```
<h1>Class Selector</h1>
<p class="blue">targets HTML elements by their class</p>
<p>More than one element can have the same class</p>
<p class="blue">Classes are used to group elements to which same style wants to be applied</p>
```
```
h1 {
    color: greenyellow;
}
.blue {
    color: blue;
}
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wjf0tc8gfqukg5e47fqg.png)

<u>Attribute Selector</u> - Targets HTML elements based on the presence of a specific attribute and optionally its value

```
<h1>Attribute Selector</h1>
<form action="">
    <label for="name">Name:</label>
    <input type="text" name="" id="">
    <br>
    <br>
    <label for="email">Email:</label>
    <input type="email" id="">
    <br>
    <br>
    <label for="password">Password:</label>
    <input type="password" id="password">
</form>
```
```
h1 {
    color: greenyellow;
}
input[type="text"] {
    background-color: yellow;
  }
input[type='password'] {
    background-color: palevioletred;
}
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iuuaezqx3n4uj2iptdkj.png)

<u>Pseudo-class and pseudo-element selectors</u> -Pseudo-class selectors target elements based on their state or user interaction. Pseudo-Elements selectors target specific parts of an element and allow you to style them independently. 

In the example below, the `:hover` pseudo-class is used to style an element when the user hovers over it with the mouse. The `::first-line` pseudo-element targets the first line of text within an element.

```
<h1>Pseudo-class Selector</h1>
    <a href="#">Hover on this link to see the color change</a>
    <h1>Pseudo-Element Selector</h1>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. 
       Est suscipit sequi vitae illo corrupti aspernatur
       necessitatibus, ex dolorem aliquam itaque ad provident 
       minima ea eius tenetur dicta laudantium omnis. Recusandae? 
       Lorem ipsum dolor sit amet consectetur adipisicing elit. 
       Voluptatibus, numquam beatae architecto nostrum voluptas 
       dolore sunt blanditiis deleniti temporibus, saepe dolores 
       nam quaerat cumque? Odit officia iste aperiam obcaecati 
       sunt?
    </p>
```
```
p::first-line {
    color: #ff0000;
    text-transform: uppercase;
  }

a:hover {
    color: #FF00FF;
  }
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h7p692tywh4t5n2r15l0.png)

<u>Universal selector</u> - target all HTML elements on a page.

```
<h1>Universal Selector</h1>
<div>
The universal selector targets all HTML elements on the page
</div>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Est suscipit sequi vitae illo corrupti aspernatur </p>
<p>necessitatibus, ex dolorem aliquam itaque ad provident minima ea eius tenetur dicta laudantium omnis. Recusandae? </p>
```
```
* {
    color:crimson;
}
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/srrrkg3no9uz6zzc05km.png)

### Types of combinators
1. <u>Descendant combinator</u> - denoted by a whitespace “ ”
2. <u>Child combinator</u> - denoted by the greater than sign **>**
3. <u>Adjacent sibling combinator</u> - denoted by the addition sign **+**
4. <u>General sibling combinator</u> - denoted by the tilde symbol **~**


## CASCADE AND SPECIFICITY
Sometimes when working on a project, directly or indirectly it is possible that you set two or more declarations with different values for the same element. This is known as **conflicting rules**. And more often than not, it is the value you do not want rendered that gets rendered(_a typical case of CSS cssing_). The understanding of specificity and cascading is required in this context as they are both the mechanisms controlling which declaration is “preferentially” picked over the other.

CSS specificity and cascade determines how styling is applied to HTML and how styling conflicts are resolved. Rule sets are said to be conflicting if and **ONLY IF** the value of the rules are different. For example if color is set to red in two different rulesets for a single element, they are not conflicting.


Cascading depends on three things, in the order of increasing importance, they are:
1. **Source order** 

This means that when there is more than one ruleset declaration with the same weight targeted at an element, the one nearer to the element is applied to it. It is <u>important</u> to note that source order only applies when the specificity or weight of both rules is the same. 

```

```

2. **Specificity**

This moves a step further than source order by applying to ruleset declarations with different weights. Ideally, different selectors have different specificity scores. A value, usually a number, is assigned to each type of selector by the browser. It is these values which when summed up gives the specificity score of a ruleset and determines which one will be picked over the other. 

Below are the different types of selectors and their specificity scores:

- Universal selectors and combinators = 0

- Type(Element) ad pseudo-type selector = 1

- Class, pseudo-class and attribute selector = 10

- Id selector = 100

- Inline styling = 1,000

- !important flag = 10,000

The specificity score is determined based on the number of elements that each selector can point to on a page. For example the universal selector points to all elements on the page and inline styling just points to a particular element. Even without the numbers, you have an idea which is more specific than the other. 

```

```

**NOTE**: Each selector has its specificity level that cannot be overwritten by another selector with low specificity. So, even if you try using 200 class selectors for an element and it has one id selector, the id selector will be picked over the 200 class selectors.

3. **Importance**

The **_!important_** is a flag which when added to a declaration, will override any other selector with a declaration that is conflicting no matter the type. Its specificity score is 10,000. 


In conclusion, it is very evident now that by understanding and applying the right selectors and rules, developers can control the styling of web elements with precision, ensuring that the desired styles are applied in the right context. CSS may initially seem daunting, but with enough practice, mastering its core concepts is possible.