Introduction
When you want to style the particular element from the HTML part, you select that element with the help of selectors in CSS. So are there any special selectors in Sass that are not present in CSS?
The answer to the above question is yes, and we are here to discuss some of them. While moving further in the article, we will discuss referencing parent selector and placeholder selector.
Placeholder Selectors Explanation
In regular CSS, we use class and id selectors specified by '.' and '#' by these symbols, respectively. But Sass gives us an edge here as there are many more selectors, one of them being a placeholder.
We have to use the @extend directive with the percentage symbol '%' to work with placeholder selectors. To display the result in the CSS, we have to use @extend.
The general syntax of placeholder selector is :
@extend %(name_of_selector); |
Example
Here we will see an example where we will change according to HTML file in scss file and see what the code reflected in the CSS file is.
Let’s look at the HTML code first:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Placeholder Selector</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Learning the working of Placeholder</h1>
<p class="first" >Sass is very useful</p>
<h2>Example of Sass</h2>
<p class="second">Here is the example of using Sass</p>
<h3>This is heading 3</h3>
<p class="third">This is the HTML code</p>
</body>
</html>
Here we have three headings corresponding to the three p tags with classes first, second, and third, respectively.
Now we have written some code in scss file to style the HTML content now just look at that:
.first{
color: rgb(55, 212, 212);
}
.second{
@extend .first;
font-size: large;
font-family: 'Courier New', Courier, monospace;
}
.third{
@extend .first;
background-color: rgb(10, 73, 75);
font-style: italic;
}
We have used the first-class style in the second and third classes using the @extend feature as it allows the selector to inherit the techniques of another selector.
Now we will see the CSS code compiled by browser:
.first, .second, .third{
color: rgb(55, 212, 212);
}
.second{
font-size: large;
font-family: 'Courier New', Courier, monospace;
}
.third{
background-color: rgb(10, 73, 75);
font-style: italic;
}
Output
To know how the following code works follow the steps given below:
- Save the above HTML code.
- Now open the saved HTML file in the browser. It should look like this:
Use of Placeholder Selector
This selector is not included in the compilation of the sass file, and because of this, it is used to create the Sass library. As shown in the above example, we can predefine some templates and use them afterward by using the @extend method.