learn2kode.in

CSS Syntax & Selectors

CSS (Cascading Style Sheets) works by selecting HTML elements and applying styles to them. Every CSS rule has two main parts: the selector and the declaration block.

CSS Syntax

A CSS rule looks like this:

selector {
  property: value;
}

Explanation

Example

p{
color:red;
font-size:18px;
font-weight:600;
}

This makes all <p> elements blue and sets their font size.

Types of CSS Selectors

CSS offers different ways to select elements depending on your need.

1. Element Selector

Selects all HTML elements with a specific tag name.

h1 {
  color: blue;
  font-size: 25px;
}

2. Class Selector

Targets elements with a specific class. Class names begin with a dot (.).

.title {
  font-weight: bold;
}

3. ID Selector

Selects an element with a unique ID. ID selectors start with a hash (#).

#header {
  background: lightgray;
}

4. Universal Selector

Applies styles to all elements.

* {
  margin: 0;
  padding: 0;
}

5. Group Selector

Used to style multiple selectors at once.

h1, h2, h3 {
  color: navy;
}

6. Attribute Selector

Selects elements based on HTML attributes.

input[type="text"] {
  border: 1px solid #333;
}

7. Pseudo-Class Selector

Used for special states like hover, focus, active, first-child, etc.

8. Pseudo-Element Selector

Targets specific parts of an element such as first letter or before/after content.

p::first-letter {
  font-size: 30px;
}

9. Descendant Selector

Selects elements inside another element.

10. Child Selector

Selects direct children only.

ul > li {
  font-size: 16px;
}