# CSS Selectors 101: A Beginner's Guide

You have written Html now you have to make it beautiful. You write Css but the address to the html tags are not accurate. Your whole effort is lost. This is why CSS Selectors are of utmost important because if you don’t use selectors properly your css will be of no use.

Consider it as a delivery address you put your time in creating a beautiful birthday card but the address is wrong your whole effort gets ruined. Similar is the case with CSS. You apply some style to a html tag and the style get applied to it.

## Understanding different types of selectors

Lets take an analogy of addressing a corporate meeting.

**Element Selector:** ‘Hello to all the Team’. Not very specific in the meeting.

**Class Selector:** ‘Hello to all the senior members of the team’. Some what specific but not too specific.

**ID Selector:** ‘Hello to Shriyansh Agarwal from the team’. Very specific.

Now lets see how to address each

### **Element Selector**

Syntax: Just the tag name eg. `p`, `h1`, `body`

CSS:

```css
p {
  color: blue;
}
```

### **Class Selector**

Syntax: Add a . in front of the class name eg. `.alert`, `.highlight`

CSS:

```css
.highlight {
  background-color: yellow;
}
```

```xml
<p>This is normal text.</p>
<p class="highlight">This text is highlighted!</p>
<span class="highlight">This is also highlighted.</span>
```

This targets the elements with class highlight.

### **ID Selector**

Syntax: Add a # in front of the id eg. `#main-header`

CSS:

```css
#unique-button {
  background-color: red;
  color: white;
}
```

```xml
<button id="unique-button">Do Not Press</button>
```

This will target the element with id `unique-button`

### Group Selectors (Efficiency)

If you want multiple elements to have the same style then we can apply style to a group of selectors.

Syntax: Selectors seperated by commas.

Css:

```css
h1, h2, p {
  font-family: Arial;
}
```

### Descendant Selectors (Context)

If you want to target a child element with a specific parent then use `parent child` syntax

Syntax: first the parent then the child eg. `div p`

CSS:

```css
footer p {
  color: gray;
  font-size: 12px;
}
```

```xml
<p>This paragraph is normal size.</p>

<footer>
  <p>This paragraph is gray and small.</p>
</footer>
```

This `p` will target only the child element of the `footer` parent

## Basic Priority (Specificity)

What happens if two rules conflict? Browsers use a point system called "Specificity" to decide which rule wins.

1. **ID Selector:** Highest Power (Most specific)
    
2. **Class Selector:** Medium Power
    
3. **Element Selector:** Lowest Power (Least specific)
    

**Example:** If you have a paragraph `<p class="alert" id="urgent">`

* `p { color: blue; }` (1 point)
    
* `.alert { color: green; }` (10 points)
    
* `#urgent { color: red; }` (100 points)
    

**Result:** The text will be **Red** because the ID is the strongest.
