CSS Selector Basics

CSS Selector Basics

Photo by Ilya Pavlov on Unsplash

Introduction

What are Selectors anyway? Selectors are simply referred to HTML elements on which CSS property should be applied for styling purposes. Let's discuss some of the common CSS selectors

Types of Selectors

1. Universal Selector

It selects all the elements on a webpage and applies styling to them. it is denoted by an asterisk mark (*)

Example

HTML

<body>
    <h1>
      This is H1 tag
    </h1>
    <h2>
      Colour and Font style changed using universal selector
    </h2>
  </body>

CSS

* {
  background-color: antiquewhite;
  font-style: italic;
}

Result

Universal-selector.png

2. Element/Type Selector

A type selector or element selector will select all elements of the given element type and styling to them

Example

HTML

<body>
    <h1>
      This is H1 tag
    </h1>
    <h2>
      Colour Changed for h1 tag
    </h2>
  </body>

CSS

body {
  background-color: antiquewhite; 
}
h1 {
  color: blue;
}

Result

Type-Selector.png

3. ID Selector

Id selector will select the element with the given Id. We use a hashtag (#) immediately followed by the case-sensitive value of the id attribute assigned to html element

Example

HTML

<body>
    <h1 id="example">
      This is simple line with id attribute
    </h1>
    <h2>
      ID cannot be repeated on a single webpage
    </h2>
  </body>

CSS

body {
  background-color: antiquewhite;
}
#example {
  background-color: grey;
  color: white;
}

Result

id-selector.png

4. Class Selector

Class selector will select all elements with the given class. We use a dot (.) immediately followed by the case-sensitive value of the class attribute assigned to html element

Example

HTML

<body>
    <h1 class="example">
      This is heading with class
    </h1>
    <p class="example">
      It is a paragraph with same class as heading
    </p>
    <h2>
      class can be repeated as many times you want
    </h2>
  </body>

CSS

body {
  background-color: antiquewhite;
}
.example {
  background-color: grey;
  color: white;
}

Result

Class-Selector.png

5. Attribute Selector

These selectors allow you to style elements having some attributes or attribute values.

Example

HTML

<body>
    <h1>This is a heading</h1>
    <p alt>This is a paragraph with atribute elemnt</p>
  </body>

CSS

body {
  background-color: antiquewhite;
}
[alt] {
  color: red;
  font-style: italic;
}

Result

Screenshot from 2022-07-20 01-39-31.png

6. Pseudo-classes

CSS pseudo-classes provide a way to style elements, based on changes to their state.

synatax

selector:pseudo { property:value; }

Example

HTML

<body>
    <h1>This is a h1 heading</h1>
    <p>Hover on h1 tag will change the background</p>
  </body>

CSS

body {
  background: antiquewhite;
}

h1:hover {
  color: blue;
  border-radius: 6px;
  background-color: #fff;
}

Result

PSEUDO-CLASSES.gif


Thanks for reading