Published: Jan. 6th, 2024
CSS serves as the style controller for your HTML documents. Understanding CSS syntax may only take seconds to grasp, but mastering it can be a more time-consuming process. This article aims to provide a comprehensive guide to CSS selectors.
A CSS statement comprises two essential components: selectors and CSS key-value pairs for the selected element. Today, we will delve into various CSS selector scenarios to help you better understand their usage.
The broadest type of CSS selector is the Tag-Wide Scope, which applies styling rules to every element of a specific HTML tag within a document. Simply put, you establish Tag-Wide Scope by specifying the name of the HTML tag to which you want to apply styling. For instance:
h1 {
font-size: 30px;
font-weight: bold;
}
The next level of CSS selector is Class-Wide Scope, which applies styling rules to every element associated with a specific class within an HTML document. To apply Class-Wide Scope, you use a period ('.') followed by the class name to designate the styling. For example:
.example-class {
text-align: center;
}
The most specific CSS selector is Element Scope, which applies styling rules to an individual element within an HTML document. To apply Element Scope, you use a ('#') followed by the element's ID to specify the styling. For example:
#exampleID1 {
text-decoration: none;
color: #000;
}
Many times, you'll require a CSS selector for a child element of a given element. You can create nested CSS selectors by placing a ('>') between selectors. Furthermore, you can specify the tag type within classname selectors. It's worth noting that you can combine Tag-Wide Scope, Class-Wide Scope, and Element Scope within nested selectors. For example:
.card-body > p > span.error-msg {
color: red;
}
If you wish to apply the same CSS styling to multiple selectors, you can employ a combination selector. This can be done by separating the CSS selectors you want to apply the same styling to with a (',') symbol. For example:
h1,h2,h3,h4,h5 {
color: black;
font-weight: bold;
}