tutorialstonight logo
A Platform To Learn To Code

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.

Example

Run the code

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>

Example

Run the code

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.

Example

Run the code

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.

Example

Run the code



BOX

BOX