HTML Classes

Class Attribute in HTML

The HTML class attribute allows you to assign one or more class names to an HTML element. This attribute is useful for applying styles with CSS and for targeting elements with JavaScript. To use a class in CSS, prefix it with a period (.) followed by the class name. You can define the class attribute in your HTML elements and then use it in your CSS styles to apply specific rules. Additionally, you can use the same class name across different elements within an HTML document.

Defining an HTML class

1.Define the Class in HTML:

Use the class attribute to assign one or more class names to an HTML element. You can apply multiple classes by separating class names with spaces.

Example:

<div class="container main-content">This is a div with two classes.</div>

2.Apply Styles Using CSS:

Use CSS to style the elements with the specified class names. Prefix the class name with a period (.) when defining styles in CSS.

Example:

<style>
.container {
width: 80%;
margin: 0 auto;
padding: 20px;
background-color: #f0f0f0;
}
.main-content {
font-family: Arial, sans-serif;
color: #333;
}
</style>