
In the previous article, we learnt how HTML helps to structure and define a web page. It helped us build the underlying skeleton of a web page. But how do we go from having a plain web page that only displays the content and gives meaning to it, to something more beautiful and pleasing to the eye?
Meet CSS! Cascading Style Sheets.
To make things simpler - if creating a webpage was like building a house, the house built with its pillars and foundational aspects in place, would be the HTML file. The paints, interior decor and aesthetics of the house can be compared to CSS.
Why do we need CSS Selectors?
Just like HTML had elements to specify each individual constituent of the page with a specific meaning, CSS has selectors. A CSS Selector tells the browser which HTML elements should have the specific attributes defined inside each of them.
Example:
p {
color: green;
}
This block specifies that every <p> (Paragraph) html element must have the colour green.
There can be different types of CSS Selectors:
Element Selector:
The above example shared indicates an element selector, which applies the attributes defined within the { } to all the paragraph elements. It selects all elements of the specified type (here, ‘p’). It is also called a ‘type’ selector.
Class Selector:
To be more specific, and only select items of a particular class, the class selector can be used. It allows us to define very specific regions - meaning any areas in the HTML document which uses the same class name. It is case-sensitive, and starts with a ‘.’.
Example:
HTML code:
<h1 class="greenbackground"> My background must be green </h1>Corresponding CSS:
.greenbackground { background-color: green; }This indicates that wherever h1 class is defined in the HTML, all those areas will have a green background (as specified within the CSS Selector attributes).
ID Selector:
This can be used to select a single individual element on the HTML page. They begin with a ‘#’ character. It applies the properties defined within, only to that specified element. The same ID cannot be used repeatedly in a page, and elements must have only one id value.
<h1 id="uniqueleement"> This specific H1 element </h1>#uniqueelement { background-color: yellow; }Group Selector:
This allows you to apply the same style to many selectors at the same time, by combining them together.
h1, .special { color: blue; }
Selectors are the foundational elements of CSS and can be studied further in detail. This blog only gives a brief overview into what they are, and different types of selectors.
Explore CSS in detail to decorate your webpages with the best designs!
