Geek Slack

Introduction to HTML
About Lesson



HTML Classes


HTML Classes

The class attribute in HTML is used to define a class name for an HTML element. This class name can then be used to apply CSS styles to multiple elements at once, or to select elements in JavaScript for manipulation.

1. Basic Usage of the class Attribute

To use the class attribute, add it to an HTML element with the desired class name. Multiple elements can share the same class name.

Example:

This paragraph is highlighted with a yellow background.

This paragraph is also highlighted with a yellow background.

<div class="highlight">
    <p>This paragraph is highlighted with a yellow background.</p>
</div>
<div class="highlight">
    <p>This paragraph is also highlighted with a yellow background.</p>
</div>

2. Applying Multiple Classes

You can apply multiple classes to a single element by separating the class names with spaces.

Example:

This paragraph is highlighted, centered, and bold.

<div class="highlight center-text bold-text">
    <p>This paragraph is highlighted, centered, and bold.</p>
</div>

3. Styling with CSS

You can define styles for class names in CSS and apply those styles to any element with the corresponding class name.

Example:

This text is blue.

This text is large.

This text is blue and large.

<style>
    .blue-text {
        color: blue;
    }
    .large-text {
        font-size: 1.5em;
    }
</style>

<p class="blue-text">This text is blue.</p>
<p class="large-text">This text is large.</p>
<p class="blue-text large-text">This text is blue and large.</p>

4. Using Classes with JavaScript

You can also use JavaScript to add, remove, or toggle classes on elements, allowing for dynamic styling and interactions.

Example:

This div can be highlighted using JavaScript.

<button onclick="document.getElementById('myDiv').classList.toggle('highlight');">Toggle Highlight</button>
<div id="myDiv">
    <p>This div can be highlighted using JavaScript.</p>
</div>

Conclusion

The class attribute is a powerful tool in HTML that allows you to apply styles to multiple elements efficiently. By using class names, you can create consistent and reusable styles across your web pages.

Join the conversation