Lesson: Using the class
Attribute in HTML and Applying CSS Classes
Introduction
The class
attribute is a fundamental feature in HTML that allows us to apply CSS styles to specific elements easily. By assigning a class name to an element, we can define its appearance using CSS rules. This makes it possible to create reusable and maintainable styles across multiple elements.
How to Use the class
Attribute
- HTML Structure
- To apply a class to an element, use the
class
attribute within the opening tag of the HTML element. - Assign a class name to the
class
attribute, ensuring it is descriptive and meaningful.
- To apply a class to an element, use the
- CSS Rules
- Define the class in your CSS using a period (
.
) followed by the class name. - Add the desired CSS properties and values.
- Define the class in your CSS using a period (
Example
HTML Code:
Copy to Clipboard
CSS Code (styles.css):
Copy to Clipboard
Output
- The first
< h1 >
element will appear in blue, centered, and larger in size. - The paragraphs with the
highlight
class will have a yellow background and black text, with padding applied.
Key Points
- Class Naming: Choose descriptive class names for better readability and maintainability.
- Dot Notation in CSS: Use a period
.
before the class name in CSS to define its styles (e.g.,.highlight
). - Reusability: A class can be applied to multiple elements, making it a powerful tool for consistent styling.
Assignment: Applying the class
Attribute
Part 1: Understanding the Basics
- Create an HTML file with the following:
- A heading with a class of
main-title
. - Two paragraphs: one with a class of
important
and another with no class.
- A heading with a class of
- Create a CSS file with styles for:
main-title
: Set the font color to green and align the text to the center.important
: Add a light gray background and italicize the text.
Part 2: Experimentation
Modify your CSS to:
- Add padding and a border to the
important
class. - Change the font size of the
main-title
.
Answer Key
HTML Code:
Copy to Clipboard
CSS Code:
Copy to Clipboard
Output:
- The
< h1 >
will appear green, centered, and larger in font size. - The
important
paragraph will have a light gray background, italic text, padding, and a black border.
Reflection Questions
- What happens if you apply multiple classes to the same element? Try it!
- How can you override styles defined by a class in your CSS?
By completing this lesson, you should now feel confident applying CSS classes using the class
attribute and understand how they can improve your web development workflow.