HTML Class
In HTML, the class
attribute is used to assign one or more class names to an HTML element. These class names can be used to apply CSS styles or to target elements with JavaScript. Classes allow you to group elements together for styling or scripting purposes.
Basic Syntax
<element class="classname">Content</element>
Example 1: Basic Usage
<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
</head>
<body>
<p class="highlight">This paragraph has a yellow background and bold text.</p>
<p>This paragraph does not have any special styling.</p>
</body>
</html>
In this example, the CSS class .highlight
is defined with a yellow background and bold text. It is applied to the first <p>
element using the class
attribute.
Example 2: Multiple Classes
<!DOCTYPE html>
<html>
<head>
<style>
.button {
background-color: blue;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
}
.large {
font-size: 1.5em;
}
</style>
</head>
<body>
<button class="button large">Click Me</button>
</body>
</html>
Here, the <button>
element has both button
and large
classes. The button
class gives it a blue background and white text, while the large
class increases the font size. Multiple classes can be added by separating them with spaces.
Example 3: Targeting Classes with JavaScript
<!DOCTYPE html>
<html>
<head>
<style>
.hidden {
display: none;
}
</style>
</head>
<body>
<p id="message" class="hidden">This message is initially hidden.</p>
<button onclick="showMessage()">Show Message</button>
<script>
function showMessage() {
document.getElementById('message').classList.remove('hidden');
}
</script>
</body>
</html>
In this example, the hidden
class is used to hide a <p>
element. When the button is clicked, a JavaScript function removes the hidden
class from the element, making it visible.
Summary
- The
class
attribute is versatile for styling and scripting. - Classes can be used to apply CSS styles and target elements with JavaScript.
- Multiple classes can be applied to an element, and they can be used in combination to achieve the desired effect.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.