A Ultimate Guide to CSS Selectors with Examples

Table of contents

1. What is Selector in CSS?

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

selector.png

2.Type of the selectors.

Basic 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.

Example

h1 {

color: blue; }

.special { color: blue; }

Class Selector

The class selector is a way to select all of the elements with the specified class name belonging to a particular attribute and apply styles to each of the matching elements.

COPY

.select{ font-size: 12px; background: springgreen; color:#130e0e; }

ID Selector

The Id selector is a way to select only the element with the specified id and apply styles to that element. It is unique on a page and can only apply to at most one element. To use an Id selector in CSS, you simply write a hashtag (#) followed by the ID of the element.

Example

# selector{

color: black;
background: yellow;
font-family: Arial, Helvetica, sans-serif;

}

Grouping selector

Selector list.

The , selector is a grouping method that selects multiple selectors and can give them properties at the same time.

Example

p, span, .button {

color: black; background-color: rgb(16, 16, 150); color: #fff; }

Combinators

Descendant combinator

It is represented by a single “ ”(space) character which helps to select an element nested inside tags.

Example

div span {

background-color: #2023d6; }

Child combinator

It is represented by > which selects an element or more than one element which is are direct children of the first element

Example

COPY

ul > li { background-color: black; margin: 10px; }

General sibling combinator combinator

It selects all elements that are next siblings of a specified element and are children of the same parent element. It is represented by ~.

Example

.element ~ p {

background-color: green; }

Adjacent sibling combinator combinator

It is represented by + which is used to select an element present after + which immediately follows the element present before +.

Example

element + p {

background-color: green; }

Pseudo classes

:root

It represents an element that is the root of the document basically the html element. Here one can create css variables to store any value such as color, border, size, etc. To access these variables one have to use var(variable-name).

Example

:root {

--primary-color: rgb(219, 47, 56); } div {

background-color: var(--primary-color); }

#iwritearticle