CSS selectors are patterns used to select HTML elements so we can apply CSS styles to them.
CSS selectors are patterns used to select HTML elements so that CSS styles can be applied to them.
1. Element Selector
An element selector selects all HTML elements of a particular type.
p {
color: blue;
}
This selects all <p> elements.
2. Class Selector
A class selector selects elements using their class attribute.
.box {
color: red;
}
It starts with a dot (.).
3. ID Selector
An ID selector selects an element using its id attribute.
#header {
background-color: blue;
}
It starts with a hash (#)An ID is normally unique on a page.
4. Attribute Selector
An attribute selector selects elements based on their attributes or attribute values.
input[type="text"] {
border: 1px solid black;
}
This selects text input elements.
5. Universal Selector
The universal selector (*) selects all elements on the page.
* {
margin: 0;
padding: 0;
}
6. Group Selector
A group selector allows you to apply the same style to multiple selectors.
h1, h2, p {
color: green;
}
7. Descendant Selector
A descendant selector selects elements that are inside another element.
div p {
color: red;
}
This selects all <p>elements inside a <div>.
8. Child Selector
A child selector (>) selects only the direct children of an element.
div > p {
color: blue;
}
9. Adjacent Sibling Selector
The adjacent sibling selector (+) selects the element immediately following another element.
h1 + p {
color: red;
}
10. General Sibling Selector
The general sibling selector (~) selects all matching siblings that come after an element.
h1 ~ p {
color: green;
}
11. Nesting Selector
The nesting selector (&) is used to show a relationship between a parent selector and its nested rules.
.box {
color: black;
& p {
color: red;
}
}
12. Pseudo-class Selector
A pseudo-class selects an element based on its state or position.
button:hover {
background-color: blue;
}
Common Examples:
:hover
:focus
:first-child
:last-child
:nth-child()
13. Pseudo-element Selector
A pseudo-element styles a specific part of an element.
p::first-letter {
font-size: 30px;
}
Common Examples:
::before
::after
::first-letter
::first-line
Top comments (0)