Class Attribute
We can access the HTML Element in many ways , they are
- By using ID
- By using class
- By using ElementName
- By using TagName
In these Page we will learn about ‘How do we access HTML element by using class name.
The class
attribute is used to specify the element in HTML . By using class attribute we can handle Multiple HTML elements.
A class attribute can be defined within <style> tag or we can separate file using the (.) character.
we can use the same class attribute name with different elements in an HTML document.
Example
<!DOCTYPE html>
<html>
<head>
<style>
.person {
background-color: purple;
color: white;
border: 5px solid black;
margin: 20px;
padding: 20px;
}
</style>
</head>
<body>
<div class="person">
<h2>Shiva Singam</h2>
<p>Software Engineer</p>
</div>
<div class="person">
<h2>Vasu Ganji</h2>
<p>Devops Developer</p>
</div>
<div class="person">
<h2>Anu Singam</h2>
<p>IAS Officer</p>
</div>
</body>
</html>
Output
In the above code we have define style for a class name is “person”, and we can use this class name with any of HTML element in which we want to provide such styling. We just need to follow the syntax to use it.
The class name ‘person’ in the above code are the same for multiple HTML elements. We can access as many as we want.
You can use multiple class names with HTML elements. These class names must be separated by a space.
Now we can try with different class names so you will understood in a better way.
Example
<!DOCTYPE html>
<html>
<head>
<style>
.person1 {
background-color: blue;
color: white;
border: 5px solid black;
margin: 20px;
padding: 20px;
}
.person2 {
background-color: green;
color: white;
border: 5px solid red;
margin: 20px;
padding: 20px;
}
.person3{
background-color: purple;
color: white;
border: 5px solid yellow;
margin: 20px;
padding: 20px;
}
</style>
</head>
<body>
<div class="person1">
<h2>Shiva Singam</h2>
<p>Software Engineer</p>
</div>
<div class="person2">
<h2>Vasu Ganji</h2>
<p>Devops Developer</p>
</div>
<div class="person3">
<h2>Anu Singam</h2>
<p>IAS Officer</p>
</div>
</body>
</html>
Output
In the above code we are used 3 different classes person1, person2, person3. In the 3 clasess we are used different colors and different border colors that you can oberserve in the output.
In the same way we can use different classes in one HTML document.
- The
class
attribute is used to specify the element in HTML . By using class attribute we can handle Multiple HTML elements. - A class attribute can be defined within <style> tag or we can separate file using the (.) character.