In the last article What is CSS and how to use it, we learned basic CSS syntax and different way of including CSS in an HTML document. We also learned about CSS declaration, ruleset, and CSS Selectors.
In this article, we will discuss the CSS Selectors in detail. We will explore Simple CSS Selectors that can be used to target desired elements for styling.
As it is said learning by doing is the best way to learn anything. In this article, we will learn Simple CSS Selectors by designing a Profile Card. Below is the final design.
Simple CSS Selectors directly select one or more elements on basis of the type of element, class or id. We will start learning different types of CSS selectors by editing below example document:
/* We are going to apply our CSS knowledge as we learn about Simple CSS Selectors in this article to design the profile card */
Simple CSS Selectors consists of
Type Selector or Element Selector matches elements on basis of tag names. For example, to match all div elements, we will write,
For the profile card we will add following type selectors in style.css file:
/* Center align content inside div */
/* Setting font properties - color, size, family and weight for paragraph */
Above styles will be applied to all div and paragraph element as matched by the selectors.
Class selector consists of a prefixed "." dot before the class name. Class name is defined in class attribute in an HTML element. Multiple HTML elements are allowed to have the same class value. Class selector matches all HTML elements with the same class name.
<img class="social-icon" src="./social/facebook.png" alt="facebook icon"/>
<img class="social-icon" src="./social/linkedin.png" alt="linkedin icon"/>
<img class="social-icon" src="./social/twitter.png" alt="twitter icon"/>
A single HTML element can also have multiple classes separated by a white space.
<img class="social-icon img-profile" src="./social/facebook.png" alt="facebook icon"/>
For the profile card we will add following class selectors in 'style.css' file:
The .img-profile class defines the style for profile image and .social-icon class styles the social icons i.e. Facebook, LinkedIn and Twitter icons.
Id selector consists of a prefixed "#" pound symbol before the id name of HTML element. Id name is defined in id attribute in an HTML element. Id should be unique in the whole document. Duplicated ids can cause unpredictable behavior.
For the profile card we will add following id selectors in 'style.css' file:
box-shadow:0px 1px 6px 0px #00000033;
These rulesets will apply unique styles to div having 'container' and 'card' id values.
Universal selector '*' selects all elements in a document.
For the profile card we will add following universal selector in 'style.css' file:
In the next article, we will explore attribute and pseudo selectors.