CSS Selectors
Learn how to target HTML elements with CSS selectors
CSS Selectors
Selectors are patterns used to select and style HTML elements.
Basic Selectors
Element Selector
/* Selects all <p> elements */
p {
color: blue;
font-size: 16px;
}
/* Selects all <h1> elements */
h1 {
color: red;
font-weight: bold;
}
Class Selector
/* Selects elements with class="highlight" */
.highlight {
background-color: yellow;
padding: 10px;
}
/* Multiple classes */
.btn.primary {
background-color: blue;
color: white;
}
ID Selector
/* Selects element with id="header" */
#header {
font-size: 24px;
text-align: center;
}
Universal Selector
/* Selects all elements */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
Attribute Selectors
/* Elements with specific attribute */
input[type="text"] {
border: 1px solid #ccc;
padding: 8px;
}
/* Attribute contains value */
a[href*="example"] {
color: green;
}
/* Attribute starts with value */
img[src^="https"] {
border: 2px solid blue;
}
/* Attribute ends with value */
a[href$=".pdf"] {
color: red;
}
Combinators
Descendant Selector
/* All <p> elements inside <div> */
div p {
margin-bottom: 10px;
}
Child Selector
/* Direct <li> children of <ul> */
ul > li {
list-style-type: disc;
}
Adjacent Sibling
/* <p> immediately after <h2> */
h2 + p {
margin-top: 0;
}
General Sibling
/* All <p> siblings after <h2> */
h2 ~ p {
color: gray;
}
Pseudo-classes
/* Link states */
a:link { color: blue; }
a:visited { color: purple; }
a:hover { color: red; }
a:active { color: orange; }
/* Form states */
input:focus {
outline: 2px solid blue;
}
input:disabled {
background-color: #f5f5f5;
}
/* Structural pseudo-classes */
li:first-child {
font-weight: bold;
}
li:last-child {
border-bottom: none;
}
tr:nth-child(even) {
background-color: #f9f9f9;
}
Pseudo-elements
/* First letter of paragraph */
p::first-letter {
font-size: 2em;
font-weight: bold;
}
/* First line of paragraph */
p::first-line {
color: blue;
}
/* Insert content before/after */
.quote::before {
content: """;
font-size: 2em;
}
.quote::after {
content: """;
font-size: 2em;
}
Selector Specificity
/* Specificity: 0,0,0,1 */
p { color: black; }
/* Specificity: 0,0,1,0 */
.text { color: blue; }
/* Specificity: 0,1,0,0 */
#content { color: red; }
/* Specificity: 1,0,0,0 */
p { color: green !important; }
Master CSS selectors to precisely target and style your HTML elements!