We need to understand what a Selector is in CSS. Without knowing this, we cannot apply styling to the elements we want to change. A Selector is used to target specific HTML elements so that we can apply style changes to those elements. In this article, we will discuss the three most commonly used types of selectors in CSS: the Tag Selector, Class Selector, and ID Selector.
Tag Selector
Tag selectors or element selectors are used to target HTML elements based on the tag name used. For example:
h1 {
color: green;
font-size: 32px;
}
We write the tag h1
in the CSS code without using the <>
symbols. Using the selector h1
will set all elements that use the tag <h1>
to appear in green and with a size of 32 pixels. Using tag selectors is very simple and easy to use. However, it is less flexible if you want to target specific elements.
Class Selector
Class Selector is used to target HTML elements that have the attribute class
. In CSS, classes are preceded by a period (.). Here is an example of its use.
HTML Code
<p class="highlight-me">This is important paragraph</p>
CSS Code
.highlight-me {
background-color: blue;
font-weight: bold;
}
The class selector .highlight-me
will appear with a blue background and bold text only on elements that have that class. The advantages of using a class selector are as follows.
- Can be used on more than one specific element.
- Suitable for creating recurring styles on many elements.
- Flexible and widely used in modern web projects.
ID Selector
ID Selector is used to target elements that have the attribute id
. In CSS, IDs begin with a hash sign (#). Here is an example of its use.
HTML Code
<h1 id="title">Main Title</h1>
CSS Code
#title {
color: gray;
text-align: center;
}
The selector #title
will only affect elements with the attribute and value id=“title”
.
Tips for Effective Selector Usage
To make CSS Selector usage more efficient and professional, it is important for us to understand when to use tags, classes, and IDs. Each selector has its own advantages and purposes, especially in real projects.
- Use class selectors for styling that is used repeatedly.
- Tag selectors can be used when the project we are building is not too complex.
- Use tag selectors to set the basic style of HTML elements globally, such as the
<body>
tag to set the background or font globally. - For truly unique elements, such as submit buttons, we can use ID selectors.
- Avoid using IDs for general styling. Because IDs have higher specificity than classes.
Conclusion
CSS selectors are the basis of all writing in CSS. With selectors, we can select HTML elements and adjust their appearance as needed.
Thank you, see you in the next article.