CSS selectors are used to target specific HTML elements and apply styles to them. There are a couple of ways we can be specific about the element we intend to select. In this chapter, we are going to focus on four basic selection methods.
1. Universal selector (*)
Universal selector is used to target all elements in the page at once. This selector is usually useful in cases of some basic formatting. Most common use of the universal selector is to remove default margins and paddings.
Example
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
2. Selecting by element name
With this approach, all elements of the one named by the selector will be styled accordingly. This will only exclude those selected differently as we will see in future examples.
Code sample:
HTML
<h3>this is heading 1</h3>
<p>this is paragraph 1</p>
<p>this is paragraph 2</p>
<p>this is paragraph 3</p>
<h3>this is heading 2</h3>
<p>this is paragraph 4</p>
<p>this is paragraph 5</p>
CSS
body{
background: lightgray;
}
h3{
color: blue;
}
p{
color: red;
}
Result
3. Selecting by id
An id is a unique identifier that sets apart an element from the other elements. Ideally, there should be only one element with the same id on a page. There could be many elements with the id attribute, but not more than one should bear the same name. Otherwise there will be nothing unique about the id. So to style an element with an id, use the id attribute to give it a name in HTML, then use the # symbol before that name, when selecting in CSS.
HTML
<body>
<h3 >this is heading 1</h3>
<p>this is paragraph 1</p>
<p >this is paragraph 2</p>
<p>this is paragraph 3</p>
<h3>this is heading 2</h3>
<p id="unique">this is paragraph 4</p>
<p>this is paragraph 5</p>
</body>
CSS
#unique{
color: green;
}
body{
background: lightgray;
}
h3{
color: blue;
}
p{
color: red;
}
Result
4. Selecting by class
Class works kind of similar to id, but in the case of class, there could be more than one element with the same class name. To style an element with a class name, use the class attribute to give it a name in HTML, then use the . symbol before that name, when selecting in CSS.
Code sample
HTML
<h3 >this is heading 1</h3>
<p class="pink">this is paragraph 1</p>
<p class="pink" >this is paragraph 2</p>
<p class="pink">this is paragraph 3</p>
<h3>this is heading 2</h3>
<p id="unique">this is paragraph 4</p>
<p>this is paragraph 5</p>
CSS
.pink{
background: pink;
}
body{
background: lightgray;
}
h3{
color: blue;
}
p{
color: red;
}
Result
Conclusion
Each selector type has its own purpose and usage. Understanding how to use each selector is crucial for effective HTML styling and layout control. Proper use of selectors can help create visually appealing and well-structured web pages, making it easier for users to interact with and understand the content presented.
Top comments (0)