DEV Community

Allan Sam
Allan Sam

Posted on

CSS Selectors

what is CSS selectors ?

CSS selectors are used to "find" (or select) the HTML elements you want to style.

We can divide CSS selectors into five categories:

-Simple selectors (select elements based on name, id, class)

Simple CSS Selectors

Basic selectors

They select element/id/class. They are also used most often and easiest to remember.

Id selector: id It selects a given element.

<div id="app">
  <div class="container">
    <p class="hello">Hello</p>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

Element selector: element_name It selects any given element.

p { color: blue; }
div { color: magenta; }
Enter fullscreen mode Exit fullscreen mode

Class selector: .class It selects all element containing given class name.

.hello {
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

ID selector: #id It selects the element containing given HTML ID.

#app {
  color: red;
}

Enter fullscreen mode Exit fullscreen mode

Universal selector: * It selects all elements.

* {
  color: yellow;
}
Enter fullscreen mode Exit fullscreen mode

The CSS Grouping Selector

The grouping selector selects all the HTML elements with the same style definitions.

Look at the following CSS code (the h1, h2, and p elements have the same style definitions):

h1 {
  text-align: center;
  color: red;
}

h2 {
  text-align: center;
  color: red;
}

p {
  text-align: center;
  color: red;
}

Enter fullscreen mode Exit fullscreen mode

Attribute selectors :

This group of selectors gives you different ways to select elements based on the presence of a certain attribute on an element:

a[href="https://example.com"]
{
}
Enter fullscreen mode Exit fullscreen mode

I hope this blogs helps to understand CSS selectors.

Top comments (0)