Introduction & type of CSS selector
Selectors are the core of CSS power. If leaners master selectors, layout becomes easy.
Think of CSS Selectors as the "addressing system" of the web. If HTML is the raw structure of your house (the walls, doors, and windows), CSS selectors are the instructions that tell the painter exactly which room needs a coat of "Ocean Blue" and which door should be "Matte Black."
In short, a selector is the part of a CSS rule that determines which HTML elements will be styled.
How it Works
A CSS selector "finds" or selects the HTML elements you want to style based on their name, ID, class, or relationship to other elements. Once selected, you apply declarations (properties and values) to change their appearance.
1. Basic Selectors
a. Element Selector
p { color: blue; }b. Class Selector
.card { background: #f4f4f4; }c. ID Selector
#header { font-size: 30px; }2. Universal Selector
Selects everything.
* {
margin: 0;
padding: 0;
}Used for CSS reset.
3. Attribute Selectors
Target elements based on attributes.
a. Basic Attribute
input[type="text"] {
border: 2px solid blue;
}b. Attribute Exists
input[required] {
background: #fff3cd;
}c. Starts With
a[href^="https"] {
color: green;
}d. Ends With
img[src$=".png"] {
border: 2px solid red;
}e. Contains
div[class*="box"] {
background: yellow;
}Very useful in real projects (like Laravel forms, dynamic components).
4. Combinator Selectors (Powerful Concept)
These define relationship between elements.
a. Descendant Selector (space)
Selects all children inside.
div p {
color: red;
}Meaning: All <p> inside <div>.
b. Child Selector (>)
Only direct child.
div > p {
color: blue;
}Only direct <p> children of <div>.
c. Adjacent Sibling (+)
Selects immediate next element.
h1 + p {
color: green;
}Selects first <p> immediately after <h1>.
d. General Sibling (~)
Selects all siblings after element.
h1 ~ p {
color: purple;
}