CSS Selectors

CSS class Selector

A CSS class selector is a type of CSS selector that selects elements based on their class attribute. In CSS, a class is defined by a (dot) . followed by the class name.

For example, if you have a class called “example” in your HTML, you would select it in your CSS with the selector .example. Once selected, you can apply CSS styles to all elements with that class.

HTML:

<p class="example">This is a paragraph.</p>
<p class="example">This is another paragraph.</p>

CSS:

.example {
  color: blue;
  font-size: 16px;
}

In this example, both of the paragraphs in the HTML will be blue and have a font size of 16px because they both have the class “example” applied to them.

The CSS selector .example is selecting all elements with a class of “example” and applying the specified styles color: blue; font-size: 16px; to those elements.

CSS Universal Selector

The CSS universal selector, represented by the asterisk *, is a selector that selects all elements on a web page. It can be used to apply styles to all elements in a document, or as a parent selector to select all child elements within a specific parent element.

For example, the following CSS code will set the margin and padding of all elements on the page to 0:

* {
  margin: 0;
  padding: 0;
}

You can also use the Universal selector as a parent selector to apply styles to all child elements within a specific parent.

div * {
  color: red;
}

In this example, all child elements within a <div> element will have their text color set to red.

It is worth noting that universal selector is the least specific selector and it should be used carefully as it would be applied to all elements on the page, this could have a performance impact on the site.

CSS Grouping Selector

CSS grouping selector allows you to select multiple elements and apply the same styles to them. Instead of repeating the same CSS styles for different selectors, you can group them together and apply the styles to all of them at once.

To group selectors, you separate them with a comma ,. For example, the following CSS code will set the font size and color for both the <h1> and <h2> elements:

h1, h2 {
  font-size: 18px;
  color: blue;
}

You can also group classes, ids, and other selectors together.

.example-class, #example-id, h3, h4 {
  font-size: 18px;
  color: blue;
}

In this example, all elements with a class of example-class, an id of example-id<h3> and <h4> will have a font size of 18px and text color of blue.

Grouping selectors is a great way to keep your CSS code organized and maintainable, it also makes it easier to make changes to multiple elements at once.

Related Posts: