CSS Selectors
What are CSS Selectors?
CSS selectors are patterns used to select the element(s) you want to style. They are a fundamental part of CSS and allow you to target specific HTML elements.
Element Selector
Selects all elements of a specific type:
Example
p {
color: blue;
}
ID Selector
Selects an element with a specific ID (use #):
Example
#header {
background-color: #4b3190;
}
Class Selector
Selects all elements with a specific class (use .):
Example
.intro {
font-size: 18px;
font-weight: bold;
}
Universal Selector
Selects all elements (use *):
Example
* {
margin: 0;
padding: 0;
}
Grouping Selectors
Select multiple elements and apply the same styles:
Example
h1, h2, h3 {
color: #4b3190;
font-family: Arial;
}
Descendant Selector
Selects elements that are descendants of a specified element:
Example
div p {
color: red;
}
Child Selector
Selects direct children of an element (use >):
Example
div > p {
color: blue;
}
Attribute Selector
Selects elements based on attributes:
Example
input[type="text"] {
border: 1px solid #ccc;
}
a[target="_blank"] {
color: red;
}
Pseudo-classes
Select elements in a specific state:
Example
a:hover {
color: #fdbb30;
}
button:active {
background-color: #4b3190;
}
input:focus {
border-color: #4b3190;
}
Pseudo-elements
Style specific parts of an element:
Example
p::first-line {
font-weight: bold;
}
p::before {
content: "Note: ";
color: red;
}