Good Morning everyone! Today I learnt about different types of selectors in CSS. There are mainly three selectors and these are:
1.CLASS: We create this by writing the tag name followed by class="some name" in whichever element we want to target. We can use the same class name for multiple elements and an element can have multiple class names also. In CSS we access the class by writing .followed by class name. For eg in the below code:
<body>
<h1 class="title">Hello World<h1>
<p>This is an example of class selector<p>
</body>
<style>
.title
{
background color:"pink";
</style>
In this the element which has the class name of title will have it's background color as pink. The same class name can be used for multiple elements and in that case all those elements will also have the same style applied.
2.ID Selector: Similar to class selector we create this selector also by writing id=some name in the element's opening tag. However we cannot use the same id for multiple elements, also an element can have only one id. This is basically so that it can be targeted effectively in JS.We can access the id selector by using #(followed by id name). For eg in the below code:
<h2>ID Selectors</h2>
<p id="para">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque
scelerisque felis velit. Mauris blandit purus ut magna aliquet
feugiat. Sed rutrum mauris et metus mattis, quis iaculis libero
viverra.</p>
<style>
#para{
color:blue;
text-align:center;
}
</style>
The element with the id para will get styled with the above mentioned styles.
3.Combinators: The final type of selector in CSS is called combinators.They are called so because they are written as a combination of two or more element names. There are four types of combinators:
1.Child Combinators:The child combinator selects all elements that are direct children of a specified element. This combinator goes only one level deep and none of the nested elements are applicable to this combinator.Eg:
<article>
<h3>Summer Sale!</h3>
<p>Get 20% off on all reusable kitchen items. Limited time only.</p>
<div>
<p>This is an example</p>
</div>
</article>
<style>
article > p
{
color:"white";
text-weight:"bold";
}
</style>
In the above code only the first p tag inside the article tag will get styled with the mentioned styles whereas the p tag inside the div tag will not be selected.
2.Descendent Combinators: These are also similar to child combinators but this one will select all the occurences of the mentioned element and not only the direct children (i.e) even nested elements will be considered. Eg:
<style>
article p{
color:"purple";
margin:"10px";
}
According to the previous example the p tag present in both the article tag and the div tag will be selected and styled accordingly.
So that's all for today...I am yet to learn about two more combinators and so I will mention them in the next post. Until then see you all!
Top comments (0)