Role of Selectors in CSS
What is Selector?
A CSS selector is the first part of a CSS Rule. It is a pattern of elements and other terms that tell the browser which HTML elements should be selected to have the CSS property values inside the rule applied to them.*
Common CSS Selectors Every Developer Should Know##
- Element or Group Selector
- #id selector
- .class selector
- Attribute selector
- Descendant selector
1. Element or Group Selector
The CSS grouping selector is used to select multiple elements and style them together. This reduces the code and extra effort to declare common styles for each element. To group selectors, each selector is separated by a space.
Syntax
The syntax for the CSS grouping selector is as follows −
element, element {
/*declarations*/
}
2. #id selector
id selector is the other most powerful common selector in CSS. Using the # symbol followed by the id name allows you to target by id and apply styling to all specified elements with a selected id. Using this selector sounds good because of its simplicity but keep in mind that the id should be unique for the entire web page. It means you cannot assign an id selector for multiple elements.
Syntax
The syntax for the CSS id is as follows −
#id {
// CSS property
}
3. .class selector
The class selector is the most useful common selector used by the developers. You can define the class selector using period (.) followed by the class name. It gives styling to all elements with a specified class attribute. It is similar to the id selector but the only difference is, the class selector allows you to target multiple elements on a page. You can also use multiple classes (separated by a space) on HTML elements.
Syntax
The syntax for the CSS id is as follows −
.class {
// CSS property
}
4. Attribute selector
Using an attribute selector, you can select all elements by the name or value of a given attribute and apply styling to them.
Syntax
The syntax for the CSS id is as follows −
selector { Property: value; }
5. Descendant selector
Descendant selectors apply styling to only those elements that are descendants of a specified element. This selector is very useful when you need to apply styling only for some specific elements. For example, what if, rather than targeting all ‘h2’ tags, you only need to target the ‘h2’ which are part of the ‘div’ tag only. These are the cases where you can use descendant selectors.
Syntax
The syntax for the CSS Descendant selector is as follows −
element > element {
// CSS Property
}
There's more to know about CSS selectors. But these were some of the commonly used CSS selectors.
Thanks for reading!