What is a CSS Selector?

CSS selectors define the elements to which a set of CSS rules apply. and, selectors are used to targeting the HTML elements on our web pages that we want to style. that select HTML elements according to its id, class, type, attribute, etc.

Grouping Selector:

The grouping selector is used to select all the elements with the same style definitions.

p {
    color: red;
} 

<p>This is a Paragraph.</p>

This is a Paragraph.

#: ID selector from Element

#paragraph {
    border: 1px solid black;
}

<p id="paragraph">This is a Paragraph.</p>

This is a Paragraph.

. : Dot Symbol

You can also specify that only specific HTML elements should be affected by a class. “means”: With this method, access to the internal Class is done through the element.

.menu{
    background-color: #ccc;
}

Or

div.menu{
    background-color: #ccc;
}

<div class="menu">
    <a href="https://honarsystems.com/">Home</a>
</div>

>: Child Combinator

X > Y is selects nodes that are direct children of the first element.

.menu > a{
    background-color: #ccc;
}

<div class="menu">
    <a href="https://honarsystems.com/">Home</a>
</div>

*: Star Symbol

The CSS universal selector (*) matches elements of any type. The star symbol will target every single element on the page. Many developers will use this trick to zero out the margins and padding.

* {
    background-color: #ccc;
}

Sometimes we want to add style to every child of the element. To achieve this we can use the star symbol like the following code.

.menu * {
    background-color: #ccc;
}

~: General Sibling Combinator

If you want to select siblings of an element even if they are not directly adjacent, then you can use the general sibling combinator (~).

.card div ~ p {
    background: #cccccc;
}

<div class="card" >
    <div>Test</div>
    <p>This is Test.</p>
</div>
Test

This is Test.

+: Adjacent Sibling Combinator

The + combinator selects adjacent siblings. This means that the second element directly follows the first, and both share the same parent.

h2 + p will match all <p> elements that directly follow an <h2>.

.example h2 + p {
    color: gray;
}

<div class="example">
    <h2>Test</h2>
    <p>This is Test.</p>
</div>

Test

This is Test.

[attribute]: Attribute Selectors

[attribute] selector is used to select elements with a specified attribute.

.example a[target="_blank"] {
    background: #cccccc;
}

<div class="example">
    <a href="https://honarsystems.com/" target="_blank">Home</a>
</div>