In CSS, simple selectors are the most basic type of selector that target elements based on their tag name, ID, class name. There used to select simple element, a group of elements, or all elements of a certain type.
#id Selectors
The #id selector styles the element with specific id.
Each ID should be unique within the document, meaning that no two elements should have the same ID.
<!-- HTML -->
<div id="my-element">
<p>Hello, world!</p>
</div>
/* CSS */
#my-element {
background-color: yellow;
}
.class Selectors
In CSS, class selectors are used to target elements based on their class attributes. A class is a way to apply a set of styles to one or more elements, without affecting other elements on the page.
<!-- HTML -->
<h1 class="heading">Heading 1</h1>
<h2 class="heading">Heading 2</h2>
<h3 class="heading">Heading 3</h3>
/* CSS */
.heading {
color: blue;
}
Tag Selector
In CSS, Tag selectors are used to target elements based on their HTML tag name.
A tag selector matches any element that has the same tag name as the selector,
<!-- HTML -->
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
/* CSS */
p {
font-size: 16px;
color: #333;
}
Other selectors related to simple selectors
| Selector | Example | Description |
|---|---|---|
| tag.class | h1.my-class { font-size:2.5rem } | Selects only h1 tag with class=”my-class” |
| * | * { margin: 0px } | A universal selector that matches any element in the HTML document |
| , | h1, h2 { color: red; } | The comma , selector is a grouping selector that allows you to apply the same styles to multiple selectors. |