HtmlCssMonk

Selectors in CSS | Learn Basic CSS

computer, computer code, programming

DESCRIPTION

CSS selectors are used to select the content you want to style. Selectors are the part of CSS rule set. CSS selectors select HTML elements according to its id, class, type, attribute etc.

There are several different types of selectors in CSS.

  1. CSS Element Selector
  2. CSS Id Selector
  3. CSS Class Selector
  4. CSS Universal Selector
  5. CSS Group Selector

Element Selector

Element selector selects the element by name.

Example –

<!DOCTYPE html>
<html>

<head>
  <style>
    p {
      text-align: center;
      color: rgb(6, 114, 114);
    }
  </style>
</head>

<body>
  <p>The lion,the witch and the wardrobe.</p>
  <p>prince caspian</p>
  <p>Voyage of the dawn treader</p>
</body>

</html>

This Code will produce the following result on your webpage –


Id Selector

The id selector selects the id attribute of an HTML element to select a specific element . Id should always be unique.

It is written with the hash character (#), followed by the id of the element.

Example –

<!DOCTYPE html>
<html>

<head>
  <style>
    #para1 {
      text-align: center;
      color: blue;
    }
  </style>
</head>

<body>
  <p id="para1">Only this paragraph will be affected.</p>
  <p>This paragraph will not be affected.</p>
</body>

</html>

This Code will produce the following result on your webpage –


Class Selector

class selector selects HTML elements with a specific class attribute.

Example –

In this example all HTML elements with class=”center” will be blue and center-aligned.

<!DOCTYPE html>
<html>

<head>
  <style>
    .center {
      text-align: center;
      color: blue;
    }
  </style>
</head>

<body>
  <h1 class="center">This heading is blue and center-aligned.</h1>
  <p class="center">This paragraph is blue and center-aligned.</p>
</body>

</html>

This Code will produce the following result on your webpage –


Universal Selector

The universal selector (*) selects all HTML elements on the page.

<!DOCTYPE html>
<html>

<head>
  <style>
    * {
      color: rgb(84, 87, 84);
      font-size: 20px;
    }
  </style>
</head>

<body>
  <h2>This is heading</h2>
  <p>This style will be applied on every paragraph.</p>
  <p id="para1">Me too!</p>
  <p>And me!</p>
</body>

</html>

This Code will produce the following result on your webpage –


Group Selector

The group selector selects all the HTML elements with the same style definitions.

Example –

<!DOCTYPE html>
<html>

<head>
  <style>
    h1,
    h2,
    p {
      text-align: center;
      color: rgb(75, 75, 77);
    }
  </style>
</head>

<body>
  <h1>Hello HtmlCssMonk.com</h1>
  <h2>Hello HtmlCssMonk.com (In smaller font)</h2>
  <p>This is a paragraph.</p>
</body>

</html>

This Code will produce the following result on your webpage –


Next topic – Box Model in CSS

Previous topic – Types of CSS


Leave a Comment

Your email address will not be published. Required fields are marked *