CSS Selectors

CSS Selectors

Hello! Welcome to the blog 🤗

I have a request. Before reading this article, please read my previous article which is HTML Basics and Fundamentals. And, please read and learn the basic concepts of CSS. Although the CSS Selectors also come under the category of basic concepts but please read and know about what CSS is, its functionality and its application.

Every CSS rule follows the general pattern.

      selector {
                key: value;
              }

where we have a selector (h2, p, form etc.) and a declaration block ( {} ) where we declare our styles. The property could be background-color, font-size, text-align and the value of the property could be red, 20px, align-centre etc.

Let’s dive into what I have for you today!



There are different types of selectors in CSS. Let us read them with examples.

Universal Selector

The universal selector selects all the elements on the webpage.

It is denoted by the asterisk (*) symbol.

Example -

  *{
        background-colour: blue;
    }

Element Selector

The element selector selects the individual HTML elements based on the tag name or element name.

Example -

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

Class Selector

The class selector selects the HTML elements which have a specific class attribute.

It is used with the dot symbol ( . ) followed by the class name.

We can use the same class name for different elements to select multiple items or apply the same style to different elements with the same class name.

For example - if we state an element with the class name para-one then we can access it in CSS with the following syntax -

.para-one{
    color: red;
}

ID selector

The id selector selects HTML elements which have the specific id attribute.

It is used with the # symbol followed by the id name.

Note: Unlike the class selector, we should use the id selector uniquely. One id name can be used for only a single element in the document and the same id name should not be used for any other elements.

HTML is very lenient and will not show any error if we use the same id name for multiple HTML elements but, this will be actually a violation of the HTML standard to use the value of ID more than once in the same document and will create a mess ultimately. So, the id should always be unique.

#para-last{
              color: green;
              text-align: center;
              }

Grouping Selector

The grouping selector is used to select multiple items and style them together. It will reduce the code and the effort as we don't need to write codes for the same style for different elements.

Example-

    h1, p, list-books{
                color: red;
                font-size: 20px;
                }

And Selector

The and selector lets us select elements which have more than one or multiple classes.

For example-

      .books.nobels{
                      font-size: 25px;
                      text-align: center;
                      }

Combinator Selectors

Descendant Selector (space)

The *descendant selector is used to select all the descendants of an element within a webpage that is, it selects all the elements that are nested inside a specific element, be it it's child or grandchild.

We use the descendant selector by selecting the parent element first and then leaving a space in the middle and then selecting the child or the grandchild.

      div p{
                color: red;
              }

Child Selector

The child selector is used to select the elements that are the direct children of a particular element. In other words, it selects only those elements that are nested directly inside the specified element and not those which are nested inside a child or grandchild of an element.

The child selector is represented by using the greater than (>) sign between two selectors. The elements represented by the second selector that are the children of the first selector are selected by using the child selector.

We use the greater than ( > ) sign between the two selectors where the first selector is the parent element and the second element is the child element.

      div > p {
           color: green;
        }

General Sibling Selector

The general sibling selector selects the elements that follow the elements of the first selector, and both elements are the children of the same parent. It can be used for selecting the group of elements that share the common parent element.

It is useful when we need to select sibling elements of the same parent even if they are not adjacent or if there are other elements between them.

The General sibling selector is represented by using a tilde (~) sign between two selectors. The first selector represents the element which has siblings after it and the second selector represents the element which is the sibling and is to be selected.

Example -

      h1 ~ p{
                color: red;
            }

Adjacent Sibling Selector

The adjacent sibling selector selects the immediate sibling of an element in a webpage. In other words, it selects those elements that are nested under the same parent as a specified element and appear immediately after that element.

The adjacent sibling selector is represented by a plus (+) sign in between two selectors. The second selector represents the element that is to be selected when it appears immediately after the element which we specify as the first selector and they both should be the children of the same parent.

The adjacent sibling selector is different from the general sibling selector as it selects only the element that appears immediately after the sibling element, whereas the general sibling selector selects any element that is targetted and appears after the sibling element.

Example -

      h1 + p{
                  font-size: 20px;
                  color: pink;
            }

Pseudo Elements

The pseudo elements are keywords which are used to add special effects to some selectors without adding more HTML in the document.

The syntax of pseudo-element is -

      selector::pseudo-element{
                               property : value;
                                }

::before selector

The ::before selector allows us to add something before the selected element's content. It works with the content property only.

The content attribute tells the browser that there should be some content and if we don't add this, it defaults to none.

Example -

::after selector

The ::after selector is similar to the ::before selector but, it also allows us to add something after the selected element's content. It works with the content property only.

The content attribute tells the browser that there should be some content and if we don't add this, it defaults to none.

One example using both the selectors -

Also, do check this out, please -

Hover over the texts and see the magic 😜

Remember: We use :: (double colon) for pseudo-elements and, we use : (single colon) for pseudo-classes.

There is a misconception with the ::before selector. Many people think that it is applied before the element which is selected but, it isn't applied before the element rather it is applied before the content of the element. It is actually applied to the element but, before the content of the element. The same is the case with the ::after selector also. In the case of ::after, it is applied to the element but, after the content of the element.

Note: Please do not use pseudo elements like ::before or ::after with images as they won't work on images.

It is not possible for me to explain the pseudo elements very elaborately here with proper examples as I am a new learner. But, I have explained as much as I could and shared the knowledge that I have till now.

Pseudo Classes

We have seen on many web pages the different behaviour of many elements. They change their style when we perform some actions. For example - some buttons change their colour or shape when clicked, and some boxes change their colour when clicked to input something. Every one must have noticed in the Google search results, some of the links turn purple once we visit them and the unvisited ones remain blue coloured. These are all done through pseudo-classes.

A pseudo-class is a keyword which defines the special state of an element. A special state includes hovering, clicking, focusing, selecting an element etc. A pseudo-class is applied to a selector for adding a special effect to it based on a particular state of an element.

Syntax of pseudo-class:-

      selector:pseudo-class{
                        property: value;
                        }

Here, the selector is the element on which we want to apply the style.

Let us see and learn some of the common pseudo-classes that are used by developers.

The link pseudo-class is used to style the element that has not been visited by the user. For example- when we see the Google search results, the unvisited links are blue in colour by default. So, we can change the style of such unvisited links with the link pseudo-class.

Example -

        a:link{
                  color: "green";
              }

Note: The links visited at least once at any time might not show the style or colour provided for the unvisited links. So, to test it properly, opening this article in Incognito mode might help.

Visited pseudo-class

The visited pseudo-class is used to style the elements that have already been visited by the user. For example - when we see the Google search results, the visited links are purple in colour by default. So, we can change the style of such visited links with the visited pseudo-class.

The visited pseudo-class allows only certain styles to be applied on the selector due to the privacy reasons of browsers.

Example -

        a:visited{
                  color: "orange";
              }

Hover pseudo-class

First of all, if you do not understand what hover means, it means to move the cursor over any element without clicking on it.

The hover pseudo-class is used to style any element when the user hovers over it. It only works when the user hovers over the element.

Note: Hover effect works only on desktops or laptops and might not work on any touchscreen devices as there is no option for mouse hover over any element in touchscreen devices.

Example -

      a:hover{
            color: red;
            background-color: yellow;
        }

Active pseudo-class

The active pseudo-class is used when the user clicks on an element or activates the state of a particular element.

While using a mouse, the activation typically means when the user presses the primary mouse button.

It is commonly used on <a> and <button> tags.

Example -

p:active{
    background-color: green;
}

Note: It is important to note that while defining the link, visited, hover and active pseudo-classes, we need to maintain a fixed order according to their specificity as, if we violate the order when defining all of them together, then the pseudo-class whose specificity is less will be overridden by the one which has a higher specificity.

The decreasing order of specificity is as follows- The acronym is LVHA-order:-

:link > :visited > :hover > :active.

Focus pseudo-class

The focus pseudo-class is used to target the element that is on focus. An element is said to be on focus when the user clicks on it.

This selector works on user input elements, generally used in forms, and is triggered as soon as the user clicks on it or taps on an element.

Example -

input:focus{
    background-color: yellow;
}

Focus-within pseudo-class

The focus-within pseudo-class selects an element that consists of a focused element as a child. The CSS rules are applied when any child element gets focused. For example- clicking on a link, selecting an input, etc.

Example -

form:focus-within{
    background-color: green;
}

nth-child pseudo-class

The nth-child pseudo-class is used to match the elements based on their position in a group of siblings. It matches every element, that is the nth-child, regardless of the type of its parent.

The syntax for the nth-child pseudo-class is -

selector:nth-child(n){
    property: value;
}

It has 2 keyword values -

  1. odd - It represents elements whose numeric position in a series of siblings is odd. eg, 1, 3, 5 etc.

  2. even - It represents elements whose numeric position in a series of siblings is even. eg, 2,4,6 etc.

It also has a functional notation

<An+B> where,

  • A represents the integer step size
  • B represents the integer offset
  • n represents any non-negative integers, starting from 0.

Example -

h2:nth-child(even){
    color: cyan;
}
h2:nth-child(odd){
    color: magenta;
}

Here, odd represents the 1st, 3rd, 5th .... children from the start, and even represents 2nd, 4th, 6th.... children from the start.

First-Child Pseudo Class

The first-child pseudo-class is used to select the first element of the parent.

It selects the first child of the parent and is very useful for styling lists.

Example -

li:first-child{
    color: crimson;
}

Last-Child Pseudo Class

The last-child pseudo-class is used to select the last element of the parent.

This is also very useful for styling lists.

Example -

li:last-child{
    color: blue;
}

So, this was all about the CSS Selectors.

To be honest, there are many many other selectors and you will just go on reading and trying them on and on but, there are some of the major selectors that are very often used and I have discussed them with proper examples.

I hope you liked them and have learnt something new from this article.

Thank You very much for reading the article ❤️🤗