Discover how you can target and style any element on your webpage with precision. From type selectors to pseudo-classes, learn how the right selector can transform your design process and create scalable, robust CSS.
CSS selectors are patterns used to target and style HTML elements. They enable you to apply declarations to precise elements on your page by selecting them based on tag names, classes, IDs, attributes, and their states.
A CSS selector is like a query language for HTML. It finds the element(s) you wish to style, allowing you to define which properties to apply. Whether you're using type, class, ID, attribute, or pseudo selectors, understanding them is fundamental to writing efficient styles.
A complete CSS rule combines a selector with a declaration block. The selector identifies the target elements and the declaration block (enclosed in braces) contains one or more declarations made up of a property and a value.
/* Type selector: styles all paragraph elements */
p {
font-size: 16px;
color: #333;
}
/* Class selector: targets elements with the class "highlight" */
.highlight {
background-color: #ffeb3b;
}
/* ID selector: targets the element with id "main-header" */
#main-header {
padding: 10px;
border: 1px solid #ccc;
}
/* Attribute and pseudo-class selector:
targets links that start with "https" on hover */
a[href^="https"]:hover {
color: #007acc;
}
Combining these selectors allows you to precisely control which elements receive your styles. This not only helps maintain consistency across your pages but also keeps your CSS organized and scalable.
Take your CSS skills to the next level by mastering advanced selectors. Learn how to combine selectors, use pseudo-classes and attribute selectors, and leverage combinators for precise targeting.
Advanced selectors enable you to pinpoint elements based on their structure and attributes. They include:
:nth-child()
or :not()
.^=
(starts with) and $=
(ends with).Utilizing these selectors allows your CSS to be more declarative and efficient while keeping your HTML clean.
/* Direct child combinator */
.container > p {
margin: 10px 0;
}
/* Adjacent sibling combinator */
h2 + p {
font-weight: bold;
}
/* General sibling combinator */
h2 ~ ul {
margin-top: 20px;
}
/* Pseudo-class: nth-child selector */
ul li:nth-child(odd) {
background-color: #f0f0f0;
}
/* Attribute selector: targets links with titles starting with "Learn" */
a[title^="Learn"] {
text-decoration: underline;
}
/* Pseudo-class: :not() selector */
.btn:not(.btn-primary) {
border: 1px solid #ccc;
}
Experiment with these selectors to write robust, maintainable CSS. Advanced selectors empower you to design responsive and dynamic layouts without adding extra classes or redundant markup.