CSS pseudo-classes


What are Pseudo-classes?

A pseudo-class is used to define a special state of an element.

For example, it can be used to:

  • Style an element when a user mouses over it
  • Style visited and unvisited links differently
  • Style an element when it gets focus

                    .example-pseudo-1  {
                      background-color: blue;
                    }
      
                    .example-pseudo-1:hover {
                      background-color: rgb(226, 43, 144);
                    }
                

                    <div class="example-pseudo-1">Mouse Over Me</div>
                

Live preview

Mouse Over Me

Syntax

The syntax of pseudo-classes:


                    selector:pseudo-class {
                      property:value;
                    }
                

CSS - The :first-child Pseudo-class

The :first-child pseudo-class matches a specified element that is the first child of another element.

Match the first .example-1 element


                      .example-1:first-child {
                        color: blue;
                      }   
                    

                      <div>
                          <p class="example-1">I am the frist child so I am blue</p>
                          <p class="example-1">I am not the first child :(</p>
                          <p class="example-1">I am not the first child :(</p>
                        </div>
                

Live preview

I am the frist child so I am blue

I am not the first child :(

I am not the first child :(


Match all <i> elements in all first child <p> elements

In the following example, the selector matches all <i> elements in

elements that are the first child of another element:


                          p i:first-child {
                            color: blue;
                          }   
                            

                        <p>I am a <i>strong</i> person. I am a <i>strong</i> person.</p>
                        <p>I am a <i>strong</i> person. I am a <i>strong</i> person.</p>
                        

Live preview

I am a strong person. I am a strong person.

I am a strong person. I am a strong person.


Previous lesson Next lesson

Spread the word:
Do you need help? Use our support forum

About the author

User avatar
Michal Szymanski
Co-Founder at MDBootstrap & BrandFlow. Entrepreneur, web developer, UI/UX designer, marketing analyst. Dancer and nerd in one.