CSS selectors are used to target and select specific HTML elements for styling. Here are some of the most commonly used CSS selectors:
Element selector
Targets all elements of a specific type. For example, p selects all <p> elements.
<p>My super paragraph!</p>p {
color: blue;
text-align: center;
}Class selector
Targets elements with a specific class attribute value. For example, .my-class selects all elements with class="my-class".
<p class="my-class">My super paragraph!</p>.my-class{
background-color:blue;
}ID selector
Targets a specific element with a unique ID attribute value. For example, #my-id selects the element with id="my-id".
<p id="my-id">My super paragraph!</p>#my-id{
background-color:blue;
}
Attribute selector
Targets elements with a specific attribute or attribute value. For example, [type="text"] selects all elements with type="text".
<p type="text">My super paragraph!</p>[type="text"]{
background-color:blue;
}
Descendant selector
Targets elements that are descendants of a specific parent element. For example, div p selects all <p> elements that are descendants of <div> elements.
<div>
<p>My super paragraph!</p>
</div>div p {
background-color:blue;
}
Child selector
Targets elements that are direct children of a specific parent element. For example, div > p selects all <p> elements that are direct children of <div> elements.
<div>
<p>My super paragraph!</p>
</div>div > p {
background-color:red;
}
Adjacent sibling selector
Targets an element that is immediately preceded by another specific element. For example, h1 + p selects the <p> element that immediately follows an <h1> element.
<h1>Title</h1>
<p>My super paragraph!</p> <!--This one will be selected -->
<p>My super paragraph!</p>h1 + p {
background-color:red;
}
Pseudo-classes
Targets elements based on a specific state or condition. For example, a:hover selects <a> elements when the mouse is hovering over them.
<a href="https://rogercodes.blog">View Blog</a>a:hover{
background-color:red;
}
Pseudo-elements
Targets a specific part of an element. For example, ::before targets the content before an element.
<h1>Header</h1>h1::before{
content: url(abc.gif);
}
Universal selector
Targets all elements on the page. For example, * selects all elements.
<p>My super paragraph 1!</p>
<p>My super paragraph 2!</p>
<p>My super paragraph 3!</p>
<p>My super paragraph 4!</p>*{
color:blue;
}These are just a few examples of the most common CSS selectors. There are many more, each serving a specific purpose. Understanding and effectively using them is essential for styling elements on a webpage.

