ID and Class Selectors

Exercise

  1. In the "index.html" file, replace the code with the following:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CSS</title>
  <link rel="stylesheet" href="./css/styles.css">
</head>
<body>
  <h1>CSS Intro</h1>
  <p>This is my first time using CSS</p>
  <p>CSS makes the website look good</p>
  <p>List of things I'm learning</p>
  <ul>
    <li>HTML</li>
    <li>CSS</li>
  </ul>
  <a href="https://www.google.com">Link to Google</a>
</body>
</html>
  1. Save.
  2. If "Live Server" is not already running, right-click anywhere in the editor and select "Open with Live Server" from the context menu.
  3. Add an "id" attribute to the h1 heading:
<h1 id="heading">CSS Intro</h1>
  1. Save.
  2. Add an "id" and "class" attribute to the first paragraph:
<p id="description" class="green">This is my first time using CSS</p>
  1. Save.
  2. Add a "class" attribute to each of the remaining paragraph:
<p class="red large">CSS makes the website look good</p>
<p class="green">List of things I'm learning</p>
  1. Save.
  2. In the "styles.css" file, replace the code with the following:
#heading {
  font-size: 50px;
}

#description {
  font-size: 30px;
}

.red {
  color: red;
}

.green {
  color: green;
}

.large {
  font-size: 100px;
}
  1. Save.
  2. In the browser, you should see the following:

  3. Exercise 2 Result

Code Walkthrough and Explanation


<h1 id="heading">CSS Intro</h1>

An id in HTML is an attribute that uniquely identifies an element within a page. It is defined in the HTML tag with the id attribute and its value is a string that is unique within the HTML document. The id attribute is used to select specific elements in CSS and JavaScript for styling and manipulation purposes.


#heading

In CSS, you use the # symbol in front of the id value from the HTML to select that specific element for styling.


<p class="red large">CSS makes the website look good</p>

A class in HTML is an attribute used to identify and group elements in a web page with the same styles. A class can be assigned to multiple HTML elements and can be used to define the styles for these elements using CSS. You can assign multiple classes to a single HTML element.


.red

The class selector starts with a dot (.) in CSS and is followed by the class value from the HTML. The CSS declarations will be applied to all HTML elements with the class.


Experiment with the Code


Video and Code References


Questions? Subscribe and ask in the video comments:



GitHub and Other References