Selectors are used in CSS to target specific HTML elements and apply styles to them. For example, the selector p applies styles to all paragraphs.
Basic selectors are the foundation of CSS. They allow you to target elements by name, class, ID, or apply styles to everything.
Targets all elements of a specific type:
p {
color: red;
}Targets any element with the specified class. Use a dot . followed by the class name:
.note {
font-style: italic;
}Targets a single, unique element by its ID. Use a hash # before the ID name:
#header {
background-color: lightgray;
}Targets every element on the page. Commonly used to reset default styles:
* {
margin: 0;
padding: 0;
}Use commas to apply the same style to multiple selectors:
h1, h2, p {
font-family: Arial;
}div p – selects all <p> inside a <div>div > p – selects only direct child <p> elements of a <div>h1 + p – selects the first <p> after an <h1>h1 ~ p – selects all <p> siblings after an <h1>Target elements based on attribute values:
input[type="text"] {
border: 1px solid #ccc;
}
a[href^="https"] {
color: green;
}
img[alt$=".jpg"] {
border-radius: 5px;
}Style elements based on state or position:
a:hover – when a link is hoveredli:first-child – the first list itemp:nth-child(2) – the second child element that is a <p>Create a CSS block using the following selectors:
h2 — set color to blue.note — italicize and gray color#main-box — set background to light yellowinput[type="text"] — add paddingli:first-child — bold the texth2 {
color: blue;
}
.note {
color: gray;
font-style: italic;
}
#main-box {
background-color: #ffffcc;
}
input[type="text"] {
padding: 5px;
}
li:first-child {
font-weight: bold;
}Ask the AI if you need help understanding or want to dive deeper in any topic