Selectors in CSS
CSS Selectors — A Quick Guide
CSS selectors are patterns used to select and style HTML elements.
1. Universal Selector
Selects all elements.
* { margin: 0; padding: 0;}2. Type (Element) Selector
Selects all elements of a given type.
p { color: blue;}3. Class Selector
Selects elements with a specific class.
.button { background: green;}4. ID Selector
Selects an element with a specific ID.
#header { font-size: 2rem;}5. Attribute Selector
Selects elements with a specific attribute or attribute value.
input[type="text"] { border: 1px solid #ccc;}6. Descendant Selector
Selects elements inside another element (at any depth).
nav a { color: red;}7. Child Selector
Selects direct children only.
ul > li { list-style-type: square;}8. Adjacent Sibling Selector
Selects the element immediately following another.
h1 + p { margin-top: 0;}9. General Sibling Selector
Selects all siblings following another element.
h1 ~ p { color: gray;}10. Pseudo-classes
Select elements in a specific state.
a:hover { color: orange;}11. Pseudo-elements
Select and style parts of elements.
p::first-letter { font-size: 2rem;}Summary Table
| Selector | Example | Selects |
|---|---|---|
| Universal | * | All elements |
| Type | div | All <div> elements |
| Class | .menu | Elements with class="menu" |
| ID | #main | Element with id="main" |
| Attribute | [type="text"] | Elements with attribute type="text" |
| Descendant | nav a | All <a> inside <nav> |
| Child | ul > li | Direct child <li> of <ul> |
| Adjacent sibling | h1 + p | <p> immediately after <h1> |
| General sibling | h1 ~ p | All <p> siblings after <h1> |
| Pseudo-class | a:hover | <a> on hover |
| Pseudo-element | p::first-line | First line of <p> |
If you want, I can create example code snippets for any selector type or explain how to combine selectors!