Home HTML CSS JavaScript React Gamedatum.com
× Home HTML CSS JavaScript React Gamedatum.com

CSS Selectors


Selectors: The Class and id

In CSS in order to style an element you must first select it and in order to do this you will need to target it using one of the two selectors below.

1. The Class Selector

The Class selector is used to select multiple elements that we want to apply the style changes.

You insert inside the opening tag of the elements you wish to change the attribute class="" and you can use any name you want. It is good practice to use a short descriptive name.

Inside the <style> </style> tags type the name you have given to the class starting with a dot (.)

For example:

                 
                  
  <!DOCTYPE html>
  <html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>The Class selector</title>
    </head>
    <style>
      .addcolor {color: red;}
    </style>
    <body>
      <p class="addcolor">The first paragraph</p>
      <p class="addcolor">The second paragraph</p>
      <p class="addcolor">The third paragraph</p>
    </body>
  </html>
                  
                  

The result:

The first paragraph

The second paragraph

The third paragraph

2. The id Selector

The id selector is used to selct a specific element that we want to style.

Insert inside the opening tag of the targeted element the attribute id="" and give it a name of your choice. As with the Class selector make sure that you use a short and descriptive name.

Now, between the <style> </style> tags type the name you have given to the id starting with a hash (#)

For example:

                 
                  
  <!DOCTYPE html>
  <html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>The Class selector</title>
    </head>
    <style>
      .addcolor {color: red;}
      #addblue {color: blue}
    </style>
    <body>
      <p class="addcolor">The first paragraph</p>
      <p id="addblue">The second paragraph</p>
      <p class="addcolor">The third paragraph</p>
    </body>
  </html>
                  
                  

The result:

The first paragraph

The second paragraph

The third paragraph