CSS Selectors
Basic Selectors
CSS
/* Element selector — targets all <p> tags */ p { color: gray; } /* Class selector — targets class="card" */ .card { background: white; padding: 1rem; } /* ID selector — targets id="header" */ #header { height: 64px; } /* Universal selector — targets EVERYTHING */ * { box-sizing: border-box; } /* Multiple selectors */ h1, h2, h3 { font-weight: 700; } /* Attribute selector */ input[type="email"] { border: 2px solid blue; } a[target="_blank"] { color: orange; }
Combinators
CSS
/* Descendant — any <p> inside .content */ .content p { color: #333; } /* Child — direct <li> children of <ul> only */ ul > li { list-style: none; } /* Adjacent sibling — <p> immediately after <h2> */ h2 + p { font-size: 1.1rem; color: #555; } /* General sibling — all <p> after <h2> */ h2 ~ p { margin-top: 0.5rem; }
Pseudo-classes
CSS
a:hover { color: #6c63ff; } /* mouse over */ a:focus { outline: 2px solid blue; } /* keyboard focus */ a:visited { color: purple; } /* already clicked */ a:active { color: red; } /* being clicked */ li:first-child { font-weight: bold; } /* first li */ li:last-child { border: none; } /* last li */ li:nth-child(2) { color: red; } /* second li */ li:nth-child(odd) { background: #f5f5f5; } /* zebra rows */ li:nth-child(even) { background: white; } input:focus { border-color: #6c63ff; } input:invalid { border-color: red; } input:valid { border-color: green; } p:not(.note) { color: #333; } /* all p except .note */
Pseudo-elements
CSS
p::first-line { font-weight: bold; } /* first line of paragraph */ p::first-letter{ font-size: 2rem; } /* drop cap */ /* ::before and ::after — inject content */ .required::after { content: ' *'; color: red; } blockquote::before { content: '"'; font-size: 3rem; color: #6c63ff; } /* Text selection color */ ::selection { background: #6c63ff; color: white; }