DEV Community

Cover image for Choosing a CSS selector
Isinkaye Praise
Isinkaye Praise

Posted on

Choosing a CSS selector

CSS, which stands for Cascading StyleSheet is the coding language which is used to give a website the layout and styles. Basically, it is used to design a website and make it aesthetically pleasing for users. It is used alongside HTML.
It can be added to the HTML file by three methods.

  • Inline - This method adds the style in the same line as the element.

  • Internal - Style is added by adding a style element in the head section of the HTML file.

  • External - An external CSS file has all the styles that will be used. The CSS file is added to the HTML document by using a link element in the head section.

Cascade refers to the mechanism that determines what CSS rule set is followed when styling a file, page or site.
When styling an HTML document, the parts/sections to be styled is chosen by using a “Selector”. A selector can either be the element tag, a class name or an id name. However, there is a level of hierarchy among the selectors.
An element wrapped in another element is referred to as the child while the wrapper is known as parent. The child/children generally inherit whatever style the parent has but sometimes, one might want a different style for a particular child.
Cascade mainly comes into play when two different styles are being applied to a specific element.
As mentioned earlier, the selectors have varying level of specificity. The element tag selector(h1 tag,p tag,a tag) is not so specific since we can have multiple tags in the HTML document. The class selector uses the class name given to some specific elements. It has a higher level of specificity than the element tag selector. On the other hand, the id selector used the id name given to an element. Note that an id can only be given to one element. It is more precise than the class selector hence, it has a higher level of specificity.
Sometimes, there might be a need to be more particular when picking an element. In such situations, one can combine two of the selectors discussed above.
It should also be noted that the method used to add CSS gives a level of specificity to the style. When styling the same element, the inline style will override the internal style which will also override the external file of style.
All these should be noted while styling to avoid errors and to achieve the desired design.

There are more tricks that can be applied to make selection easier. For more information, you can check out MDN web docs -

Top comments (0)