CSS Selectors

CSS Selectors

What is CSS Selectors

A CSS selector is the first part of a CSS Rule. It is a pattern of elements and other terms that tell the browser which HTML elements should be selected to have the CSS property values inside the rule applied to them.

Example

p {
  color: gray;
}

.class {
  color: red;
}

Type of CSS selectors

  • Universal Selector

    The asterisk (*) is known as the CSS universal selectors. It can select whole the HTML page with all types of elements. The asterisk can also be followed by a selector while used to select a child object. This selector is useful when we want to select all the elements on the page.
* {
   margin: 0;
   padding: 0;
   box-sizing: border-box;
}
  • Element Selector

    The element selector selects HTML elements based on the element name.
h1 {
  background-color: green;
}

div {
  background-color: lightblue;
}

p {
  background-color: yellow;
}
  • Class Selector

    The class selector selects HTML elements with a specific class attribute. To select elements with a specific class, write a period (.) character, followed by the class name.
.center {
  text-align: center;
  color: red;
}
  • Id Selector

    The id selector uses the id attribute of an HTML element to select a specific element. The id of an element is unique within a page, so the id selector is used to select one unique element! To select an element with a specific id, write a hash (#) character, followed by the id of the element.
#para1 {
  text-align: center;
  color: red;
}
  • 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, h2, p {
  text-align: center;
  color: red;
}
  • Descendant Selector

    The descendant selector matches all elements that are descendants of a specified element. The following example selects all <p> elements inside <div> elements:
div p {
  background-color: yellow;
}
  • Child Selector (>)

    The child selector selects all elements that are the children of a specified element. The following example selects all <p> elements that are children of a <div> element:
div > p {
  background-color: yellow;
}
  • Adjacent Sibling Selector (+)

    The adjacent sibling selector is used to select an element that is directly after another specific element. Sibling elements must have the same parent element, and "adjacent" means "immediately following". The following example selects the first <p> element that are placed immediately after <div> elements:
div + p {
  background-color: yellow;
}
  • General Sibling Selector (~)

    The general sibling selector selects all elements that are next siblings of a specified element. The following example selects all

    elements that are next siblings of

    elements:
div ~ p {
  background-color: yellow;
}