CSS Selectors
Selectors are patterns used to select the elements you want to style.
- Universal Selector:
*
- Type Selector:
p, h1
- Class Selector:
.classname
- ID Selector:
#idname
- Attribute Selector:
[type="text"]
- Descendant Selector:
div p
- Child Selector:
ul > li
- Adjacent Sibling Selector:
h2 + p
- General Sibling Selector:
h2 ~ p
- Pseudo-class Selector:
a:hover, li:first-child
- Pseudo-element Selector:
p::first-line, h1::after
Examples
Universal Selector:
•Selects all elements on a page.
•Useful for applying global styles.
* { margin: 0; }
Type Selector:
•Selects elements by their HTML tag name.
p { color: blue; }
Class Selector:
•Targets elements with a given class.
•Can be reused on multiple elements.
.highlight { background: yellow; }
ID Selector:
•Targets elements with a given ID.
•IDs must be unique within a page.
#main-title { font-size: 2em; }
Attribute Selector:
•Apply the same style to multiple elements at once.
Code: input[type="text"] { border: 1px solid #333; }
Descendant Selector:
•Selects elements that are descendants of a specified element.
Code: div p { margin-bottom: 10px; }
Child Selector:
•Selects elements that are direct children of a specified element.
Code: ul > li { list-style: square; }
Adjacent Sibling Selector:
•Selects the element that comes immediately after another element.
Code: h2 + p { font-weight: bold; }
General Sibling Selector:
•Selects elements that are siblings of a specified element.
Code: h2 ~ p { color: green; }
Pseudo-class Selector:
•Apply styles to elements in a special state (like hover, visited, focus).
Code: a:hover { color: red; }
Pseudo-element Selector:
•Style a part of an element (like first letter, first line).
Code: p::first-line { font-weight: bold; }