The CSS Selectors are used to target specific elements in an HTML document to assign value for their property to apply styles to them.
There are almost 9 type of selectors in CSS.
- Element Selectors
- Class Selectors
- ID Selectors
- Universal Selector
- Descendant Selectors
- Child Selectors
- Adjacent Sibling Selectors
- General Sibling Selectors
- Attribute Selectors
It targets the elements based on their tag name.
Syntax: tag_name
p {
color: blue;
}
It targets elements based on a class attribute.
Syntax: .class_name
<div class="my-class">This is a div with some content</div>
.my-class {
font-weight: bold;
}
It targets a single element based on its unique ID attribute.
Syntax: #id_name
<h1 id="my-heading">This is a heading</h1>
#my-heading {
text-align: center;
}
It targets all elements in the HTML document.
Syntax: *
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
It targets elements that are descendants of another element.
Syntax: parent_element child_element
div p {
color: green;
}
It targets elements that are direct children of another element.
Syntax: parent_element > child_element
div > p {
color: green;
}
It targets the next element that is a sibling of the current element.
Syntax: element1 + element2
p + span {
font-style: italic;
}
It targets all elements that are siblings of the current element.
Syntax: element1 ~ element2
h1 ~ p {
color: red;
}
It targets elements based on their attributes.
Syntax:
[attribute_name]
[attribute_name="value"]
[attribute_name^="value"] (starts with)
[attribute_name$="value"] (ends with)
[attribute_name*="value"] (contains)
Apply style to the a tag having the attribute name
a[href] {
color: blue;
}
Apply style to the a tag with attribute value equals to
aboutus.html
a[href="aboutus.html"] {
color: blue;
}
Apply style to the a tag with attribute value starts with
https://
a[href^="https://"] {
color: blue;
}
Apply style to the a tag with attribute value ends with
.html
a[href$=".html"] {
color: blue;
}
Apply style to the a tag with attribute value contains
products
a[href*="products"] {
color: blue;
}