Advertisement

Responsive Advertisement

HTML CLASS ATTRIBUTE | HTML CLASS

HTML Class Attribute

The HTML class attribute is used to specify a class for an HTML element.

Multiple HTML elements can share the same class.

The class Attribute

The class attribute is commonly used to assign a class name to an HTML element. This class name can be used in CSS to apply the same styles to multiple elements. It can also be used in JavaScript to access and manipulate elements with a specific class name.

Example

<!DOCTYPE html>
<html>
<head>
<style>
.city {
background-color: tomato;
color: white;
border: 2px solid black;
margin: 20px;
padding: 20px;
}
</style>
</head>
<body>

<div class="city">
<h2>London</h2>
<p>London is the capital of England.</p>
</div>

<div class="city">
<h2>Paris</h2>
<p>Paris is the capital of France.</p>
</div>

<div class="city">
<h2>Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>
</div>

</body>
</html>

Another example using the span element:

<!DOCTYPE html>
<html>
<head>
<style>
.note {
font-size: 120%;
color: red;
}
</style>
</head>
<body>

<h1>My <span class="note">Important</span> Heading</h1>

<p>This is some <span class="note">important</span> text.</p>

</body>
</html>

Tip: The class attribute can be used with any HTML element.

Note: Class names are case-sensitive.

The Syntax for Class

To create a class, write a period (.) followed by the class name. Then define the CSS properties inside curly braces {}.

Example

<!DOCTYPE html>
<html>
<head>
<style>
.city {
background-color: tomato;
color: white;
padding: 10px;
}
</style>
</head>
<body>

<h2 class="city">London</h2>
<p>London is the capital of England.</p>

<h2 class="city">Paris</h2>
<p>Paris is the capital of France.</p>

<h2 class="city">Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>

</body>
</html>

Multiple Classes

An HTML element can belong to more than one class.

Separate multiple class names with a space.

Example

<h2 class="city main">London</h2>
<h2 class="city">Paris</h2>
<h2 class="city">Tokyo</h2>

The first <h2> element belongs to both the city and main classes and receives the styles from both.

Different Elements Can Share the Same Class

Different HTML elements can use the same class name.

Example

<h2 class="city">Paris</h2>

<p class="city">
Paris is the capital of France.
</p>

Both elements will share the same CSS styles.

Using the class Attribute in JavaScript

JavaScript can access elements with a specific class name using the getElementsByClassName() method.

Example

<script>
function myFunction() {
var x = document.getElementsByClassName("city");

for (var i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
}
</script>

When the myFunction() function is called, all elements with the class name city will be hidden.

Post a Comment

0 Comments