ID and Class Selectors
Exercise
- 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>
- Save.
- If "Live Server" is not already running, right-click anywhere in the editor and select "Open with Live Server" from the context menu.
- Add an "id" attribute to the h1 heading:
<h1 id="heading">CSS Intro</h1>
- Save.
- Add an "id" and "class" attribute to the first paragraph:
<p id="description" class="green">This is my first time using CSS</p>
- Save.
- 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>
- Save.
- 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; }
- Save.
- In the browser, you should see the following:
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
- Try adding the
red
class to the first<li>
element. - Try adding a new class to the second
<li>
element and then write thecss
to make the colorblue
.
Video and Code References
Questions? Subscribe and ask in the video comments: