10 Jul CSS Selectors
With CSS selectors, select the elements based on their element name, id, class, etc. Here, we will learn about element selectors, class selectors, id selectors, and universal selectors. With that, we will also see how to group CSS selectors to ease our work and minimize the code.
Let’s begin with the CSS element selector,
The CSS element selector
Under the element selector, you need to set the property and value for the element. Here, we will add color to all the level 2 headings,
1 2 3 4 5 |
h2 { color: #c70039 ; } |
The CSS universal selector
Under the universal selector, you must set property and value for any element. Yes, the declaration will work for every element. Here, we will add color to any element,
1 2 3 4 5 |
* { color: #c70039 ; } |
The CSS ID selectors
Use the id attribute of an element to define the style rules. For selecting an element with a specific id, you need to use the hash (#) character. Just mention the hash character, followed by the id of the element. Always remember, the id of the element should be unique within a web page.
Here, for example, we will apply the style rule to all the elements with id =”content”. This works for every element with the id attribute set to content,
1 2 3 4 5 6 |
#content { color: #6E4253; font-size: 15px; } |
The CSS class selectors
Use the class attribute of an element to define the style rules. For selecting an element with a specific class, you need to use a period (.) character. Just mention the period character, followed by the class of the element.
Here, for example, we will apply the style rule to all the elements with class =”content”. This works for every element with the class set to main.
1 2 3 4 5 6 |
.main { margin-top: 10px margin-bottom: 10px } |
Grouping Selectors
As the name says, grouping selectors means grouping the selectors with the same style definitions. Let’s say we have the following four elements with the same style definitions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
h1 { color: #d4e6f1; font-family: "Times New Roman"; font-weight: bold; } h2 { color: #d4e6f1; font-family: "Times New Roman"; font-weight: bold; } h3 { color: #d4e6f1; font-family: "Times New Roman"; font-weight: bold; } p { color: #d4e6f1; font-family: "Times New Roman"; font-weight: bold; } |
To minimize the code, we can group the above selectors’ h1, h2, h3, p since they have the declarations. Here’s the enhanced form after grouping selectors,
1 2 3 4 5 6 7 |
h1, h2, h3, p { color: #d4e6f1; font-family: "Times New Roman"; font-weight: bold; } |
No Comments