Resources | Subject Notes | Information Communication Technology ICT
This section explores how to use CSS classes to structure and style elements within a web page. Classes provide a way to apply the same styling to multiple elements, making your code more maintainable and organized.
A CSS class is a name that you assign to HTML elements. You can then use this class name in your CSS stylesheet to define the visual properties (like color, font, size, layout) of those elements. Multiple elements can share the same class.
To apply a class to an HTML element, use the class
attribute. The value of the class
attribute is a space-separated list of class names.
Example:
<p class="important highlight">This is an important paragraph.</p>
In this example, the paragraph element has two classes: "important"
and "highlight"
.
Let's create a simple web page with classes to structure the content.
Here's the HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Classes Example</title>
<style>
.header {
background-color: #f0f0f0;
padding: 20px;
text-align: center;
}
.navigation {
list-style-type: none;
padding: 0;
}
.navigation li {
display: inline;
margin-right: 10px;
}
.main-content {
margin: 20px;
}
.footer {
background-color: #f0f0f0;
padding: 10px;
text-align: center;
font-size: 12px;
}
.highlight {
font-weight: bold;
color: blue;
}
</style>
</head>
<body>
<header class="header">
<h1>My Website</h1>
</header>
<nav class="navigation">
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>
<main class="main-content">
<p class="important highlight">This is the main content of the page. This paragraph is important and highlighted.</p>
<p>More content here.</p>
</main>
<footer class="footer">
<p>Copyright © 2023</p>
</footer>
</body>
</html>
An HTML element can have multiple classes, separated by spaces. This allows you to combine different styles for a single element.
Example:
<p class="important highlight">This text is both important and highlighted.</p>
In your CSS stylesheet, you can use the .
selector to target elements with a specific class.
Example:
.important {
color: red;
}
.highlight {
font-style: italic;
}
This CSS will make any element with the class "important"
red and any element with the class "highlight"
italic.
Using CSS classes is a fundamental aspect of website authoring. It promotes code reusability, organization, and maintainability, making it easier to create and update web pages.
Create a simple web page with a heading, a paragraph, and a list. Apply different CSS classes to these elements to change their appearance. Experiment with different class names and styles to see how they affect the layout and visual presentation of your page.