Introduction to CSS Selectors
CSS Selectors are used for targetting the HTML elements to style them. The first part of the CSS rule is the CSS selector, we write the CSS selector first and after that, the rule is written. The selected HTML elements are known as the subject of the selector.
Individual Selectors
We can select the HTML elements by individual selectors or a combination of selectors. The individual selectors can be HTML tag names like h1, h3, p, a, img etc. for selecting the heading, paragraph, anchor, and image respectively. Below is the example of individually selecting the HTML elements:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>CSS Basics Assignment</title>
</head>
<body>
<h2>CSS selectors</h2>
<p> This is an example paragraph, styled using the "p" tag. </p>
</body>
</html>
h2 {
color: #ff0000;
}
p {
letter-spacing: 2px;
}
Output:
In the above code snippet, the paragraph and heading are selected and applied differently colours to them.
We can select any HTML element using the tags, but it is not always the best way to target the HTML elements because it will select all the HTML elements containing the tags. To solve this problem, we have different selectors like class selector, id selector descendant selector, child selector etc.
Class Selectors
To target the HTML elements using the class selectors we have to add the class attribute inside the HTML tag. The class name is further used to apply the styling to the element we want. To apply a style using class selectors period (.) symbol is used before the class name. For example, if the class name is "dummy", and we have added the class name dummy to the heading tag, then the CSS rules will be applied only to that heading element whose class name is "dummy", remaining heading tags will be unaffected.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Basics Assignment</title>
</head>
<body>
<h2 class="dummy">I am a heading having class "dummy"</h2>
<p> This is an example paragraph, styled using the "p" tag. </p>
<h2>I am a normal heading.</h2>
</body>
</html>
.dummy {
color: #15066d;
}
Output:
Id Selectors
Another way to select the HTML elements is using Id Selectors. The pound (#) symbol is written before the id name to target the element containing that id. The id selectors are similar to class selectors but the main difference between id and class selectors is the order of preference. Id selectors have greater precedence than class selectors. It is recommended to use the id selector once per page, the class selectors can be repeated, but id selectors shouldn't.
Example of id selectors:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Basics Assignment</title>
</head>
<p id="dummy-para">I am a paragraph and my id is "dummy-para"</p>
<p>I am a normal paragraph.</p>
<body>
</body>
</html>
#dummy-para {
color: #44ff88;
background-color: grey;
}
Output:
Below are the good and bad practices:
Good Practice:
We can use the same class name multiple times, but the id name must be unique.
Bad Practice:
It is not recommended to use a single id selector multiple times.
Universal Selectors
The universal selector selects everything in the document, and the asterisk (*) symbol is used before the CSS rule.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Heading</h1>
<p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Animi ullam esse, soluta eligendi harum maiores necessitatibus aut accusamus molestiae ex aspernatur, neque dignissimos iure in libero minima amet veniam obcaecati repudiandae similique! Possimus, minima.</p>
</body>
</html>
* {
background-color: rgb(247, 247, 54);
}
Output:
And Selector
And selector is similar to the AND logic, as we know AND will be true only when both the conditions are true, similarly in the case of And Selector the CSS rules will be applied when both selectors are present in the HTML element.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2 class="red first-heading">Red Heading</h2>
<p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Animi ullam esse, soluta eligendi harum maiores
necessitatibus aut accusamus molestiae ex aspernatur, neque dignissimos iure in libero minima amet veniam
obcaecati repudiandae similique! Possimus, minima.</p>
<h2 class="red">Heading but not red</h2>
<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Doloremque soluta repudiandae officia nisi facere, a, blanditiis quos, laboriosam dolorum quaerat corporis quasi aliquam!</p>
</body>
</html>
h2.red.first-heading {
background-color: #ff0000;
}
Output:
We can see in the output, the first heading is red but the second heading is not red, this happens because the second heading contains only the "red" class and the first heading contains both the classes, so the AND condition fulfils and the CSS rule is applied to the first heading only.
Selecting inside an element
Suppose we have to select an HTML element inside another HTML element, in that case, the descendant selectors and child selectors are used.
Descendant Selectors
Descendant selectors select all the elements inside the parent HTML element. The space is used between two selectors, the syntax and example of descendant selectors are given below:
selector_1 selector_2 {
/*CSS Styles*/
}
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Descendant</title>
</head>
<body>
<div class="parent">Parent
<div class="child">Child 1
<div class="grandchild">
Grandchild
</div>
</div>
<div class="child">Child 2
<div class="grandchild">
Another Grandchild
</div>
</div>
</div>
</body>
</html>
.parent .child {
background: red;
}
Output:
We can see all the children and grandchildren are selected.
Child Selector
Child selector is used to select the immediate child of the parent, in this case, the grandchildren, and great-grandchildren are omitted. Greater than (>) symbol is used in between the selectors to select the immediate child.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Child Selector</title>
</head>
<body>
<div class="parent">
<div class="child">Child 1
<p>I am not an immediate child of parent class.
<section>I am a section inside a paragraph which is inside a child class.</section>
</p>
</div>
<p>I am a paragraph.</p>
<div class="child">Child 2
<p>I am a paragraph inside a child class.</p>
</div>
</div>
</body>
</html>
.parent > section {
background: red;
}
Output:
In the above example, the style is not applied to the section because the section is not the immediate child of the parent class. If we replace the child selector (>) with the descendant selector ( ), the style will be applied to the section as shown below.
Replacing the child selector with the descendant selector in the above example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Child Selector</title>
</head>
<body>
<div class="parent">
<div class="child">Child 1
<p>I am not an immediate child of parent class.
<section>I am a section inside a paragraph which is inside a child class.</section>
</p>
</div>
<p>I am a paragraph.</p>
<div class="child">Child 2
<p>I am a paragraph inside a child class.</p>
</div>
</div>
</body>
</html>
.parent section {
background: red;
}
Output:
Sibling Selector
Siblings are the adjacent child of the parent, they are at the same level of the hierarchy. The addition (+) or tilde (~) symbol can be used to select the siblings.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Child Selector</title>
</head>
<body>
<div class="parent">
<div class="child">Child 1
<p>I am not an immediate child of parent class.
<section>I am a section inside a paragraph which is inside a child class.</section>
</p>
</div>
<p>I am a paragraph.</p>
<div class="child">Child 2
<p>I am a paragraph inside a child class.</p>
</div>
</div>
</body>
</html>
p+div {
background: pink;
}
OR
p~div {
background: pink;
}
Output:
In the example, we can see that the pink background is applied to the div which is a sibling of the paragraph, the remaining divs and paragraphs are unaffected. The one thing to notice is the order of the tag matters in this case, in the above example we are selecting div after paragraph, let's change the order and observe the output. In this case, the HTML code remains the same, only CSS is changed.
Changing the order of the tags in the above example:
div~p {
background: pink;
}
OR
div+p {
background: pink;
}
Output:
In this case, the paragraph which is a sibling of div is selected.
Pseudo Selectors in CSS
There are two types of pseudo selectors in CSS, pseudo-classes and pseudo-elements. Pseudo selectors are targetting the elements in a very specific state.
Pseudo-classes
Pseudo-classes are defined using the colon (:) symbol, when a pseudo-class is applied it seems that a new class is added to the element in a certain state. An example of a pseudo-class is given below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pseudo selectors</title>
</head>
<body>
<section>
<p>This is first paragraph.</p>
<p>This is second paragraph.</p>
<p>This is third paragraph.</p>
</section>
</body>
</html>
section p:first-child {
color: purple;
}
Output:
Another pseudo-class is dynamic pseudo-classes, it will work only when the user interacts. The examples of dynamic pseudo-classes are :hover, :focus etc.
Example of dynamic pseudo-class:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pseudo selectors</title>
</head>
<body>
<section>
<p>This is first paragraph. Lorem ipsum dolor sit amet consectetur adipisicing elit. Animi distinctio reiciendis
earum, magnam harum cumque itaque, perferendis corrupti, recusandae accusantium soluta. Ad, natus.</p>
<p>This is third paragraph. Lorem ipsum dolor sit amet consectetur, adipisicing elit. Doloribus amet quia porro
consectetur obcaecati illum exercitationem quisquam mollitia sit possimus, eveniet nobis officia? Quaerat
voluptate ducimus deserunt nesciunt rerum facilis, temporibus eligendi pariatur magnam.</p>
</section>
</body>
</html>
section p:hover {
color: purple;
}
Output:
Before hover
On hover
The text colour changes from black to purple, only on hover otherwise remains black.
Pseudo-elements
Pseudo-elements are defined using a double colon (::) symbol, when a pseudo-element is used, it seems that a whole new element is added in a certain state.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pseudo selectors</title>
</head>
<body>
<section>
<p>This is first paragraph. Lorem ipsum dolor sit amet consectetur adipisicing elit. Animi distinctio reiciendis
earum, magnam harum cumque itaque, perferendis corrupti, recusandae accusantium soluta. Ad, natus.</p>
<p>This is third paragraph. Lorem ipsum dolor sit amet consectetur, adipisicing elit. Doloribus amet quia porro
consectetur obcaecati illum exercitationem quisquam mollitia sit possimus, eveniet nobis officia? Quaerat
voluptate ducimus deserunt nesciunt rerum facilis, temporibus eligendi pariatur magnam.</p>
</section>
</body>
</html>
section p::first-line{
color: purple;
}
Output:
In the above example, the first line of each paragraph is targeted. It seems that a whole new element is added, the first line will always be targeted even if the window size is changed. It will not be possible without pseudo-element, we can not guess the exact sentence which will appear in the first line of a paragraph.
::before and ::after
As the name suggests ::before & ::after can be used to add some string before and after any element in the document using CSS. Mostly empty strings are used to apply styling with the help of ::before and ::after selectors. Some examples are shown below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pseudo selectors (::before and ::after)</title>
</head>
<body>
<section>
<p>This is first paragraph. Lorem ipsum dolor sit amet consectetur adipisicing elit. Animi distinctio reiciendis
earum, magnam harum cumque itaque, perferendis corrupti, recusandae accusantium soluta. Ad, natus.</p>
<p>This is third paragraph. Lorem ipsum dolor sit amet consectetur, adipisicing elit. Doloribus amet quia porro
consectetur obcaecati illum exercitationem quisquam mollitia sit possimus, eveniet nobis officia? Quaerat
voluptate ducimus deserunt nesciunt rerum facilis, temporibus eligendi pariatur magnam.</p>
</section>
</body>
</html>
section p::before {
content: "This will be added before first sentence of paragraph.";
color: red;
}
Output:
A new sentence is added using ::before pseudo-element, the sentence can be also added after the paragraph using ::after selector as shown below.
section p::after {
content: "This will be added after last sentence of paragraph.";
color: red;
}
Output:
The last sentence is added using the ::after selector inside the CSS.
Thanks for reading and best of luck ๐.