HTML CLASSES
HTML has an attribute called class attribute.
you can think about class as a box of defined CSS properties, when you mention a class to any element then that element gets all the CSS property specified for that class.
A class is defined either in an external CSS document or inside <style> tag.
A class is defined starting with a dot ( . ) followed by class name. All CSS properties are
specified after that inside the curly braces
Defining and using a HTML class
To define a class :
- step 1: create a <style> tag in <head> tag. :
- Step 2: write the name of your class starting with a dot ( . ) . :
- step 3 : Make curly braces.Define the CSS properties in side curly braces.
- step 4 : Create a class attribute inside the tag you want to define those CSS properties and give it the name of your class within a double quote.
<!DOCTYPE html>
<html>
<head>
<style>
.class-name {
color: red;
font-size: 20px;
}
</style>
</head>
<body>
<h2>This is not given any class.</h2>
<p class="class-name">This paragraph has class named "class-name".</p>
</body>
</html>
Try It
Multiple classes in single element
Multiple classes can be added to a single tag by giving a space between the class names.
Example: <p class="class1 class2 class3">...content...</p>
<!DOCTYPE html>
<html>
<head>
<style>
.class1 {
color: white;
font-size: 20px;
}
.class2 {
background-color: #006699;
}
</style>
</head>
<body>
<h2>This is not given any class.</h2>
<p class="class1 class2">This paragraph has 2 classes named class1 and class2.</p>
</body>
</html>
Try It
Adding class to similar objects
The class attribute can be added on any tag and a specific class added to any number of times.
All tags having the same class have the same properties.
<!DOCTYPE html>
<html>
<head>
<style>
.a-fruit {
color: white;
background-color: orange;
font-size: 20px;
text-align: center;
height: 100px;
width: 100px;
border-radius: 50%;
}
</style>
</head>
<body>
<h2>All fruits are given same class named a-fruit.</h2>
<p class="a-fruit">Apple</p>
<p class="a-fruit">orange</p>
<p class="a-fruit">papaya</p>
</body>
</html>
Try It
Adding CSS property to class by javascript
A class can be given CSS property by any event on the webpage like- onclick(), onload(), onmouseover() etc.
To add any CSS property by javascript first we have to select that class using javascript DOM.
We can select the class using document.getElementsByClassName("class-name") and call a function over any event targeting these classes.
<!DOCTYPE html>
<html>
<head>
<script>
function addcolor() {
var elements = document.getElementsByClassName("change-color");
for (var i = 0; i < elements.length; i++) {
elements[i].style.color = "red";
elements[i].style.fontSize = "25px";
}
}
</script>
</head>
<body>
<h2>Adding CSS property to a class using javascript.</h2>
<button onclick="addcolor()">change color</button>
<p class="change-color">Apple</p>
<p class="change-color">orange</p>
<p class="change-color">papaya</p>
</body>
</html>
Try It