Mastering CSS starts with understanding selectors! They're how you tell your browser EXACTLY what to style.
This cheat sheet covers the most common (and some advanced!) selectors to level up your styling game. Save it, share it, and you will never forget how to target your elements like a pro! π―
- Selector:
* - Code:
* { box-sizing: border-box; }
- Meaning: Styles ALL elements on the page.
- Selector:
p - Code:
p { font-size: 16px; }
- Meaning: Styles all
<p>(paragraph) elements.
- Selector:
.my-class - Code:
.my-class { color: blue; }
- Meaning: Styles all elements with
class="my-class".
- Selector:
#my-id - Code:
#my-id { background-color: #eee; }
- Meaning: Styles the single element with
id="my-id".
- Selector:
[type="text"] - Code:
[type="text"] { border: 1px solid gray; }
- Meaning: Styles all elements that have
type="text".
- Selector:
div p - Code:
div p { margin-left: 20px; }
- Meaning: Styles any
<p>tag that is inside a<div>tag.
- Selector:
ul > li - Code:
ul > li { list-style: none; }
- Meaning: Styles
<li>tags that are direct children of a<ul>.
- Selector:
h1 + p - Code:
h1 + p { margin-top: 20px; }
- Meaning: Styles a
<p>tag that comes immediately after an<h1>tag.
- Selector:
h1 ~ p - Code:
h1 ~ p { color: #333; }
- Meaning: Styles all
<p>tags that are siblings of an<h1>(after it, same parent).
- Selector:
h1, h2, h3 - Code:
h1, h2, h3 { font-family: sans-serif; }
- Meaning: Applies the same style to
<h1>,<h2>, AND<h3>elements.
- Selector:
a.button - Code:
a.button { display: block; }
- Meaning: Styles
<a>tags that also have theclass="button".
- Selector:
a:hover - Code:
a:hover { text-decoration: underline; }
- Meaning: Styles
<a>tags when the mouse is over them.
- Selector:
li:nth-child(even) - Code:
li:nth-child(even) { background-color: #f0f0f0; }
- Meaning: Styles every even-numbered
<li>within its parent. (Useoddfor odd, or3for the third).
- Selector:
p::before - Code:
p::before { content: "β "; }
- Meaning: Inserts a star before the content of every
<p>tag.
- Selector:
::selection - Code:
::selection { background: yellow; color: black; }
- Meaning: Styles text when it is selected/highlighted by the user.