HTML class Attribute

HTML Tutorial

HTML class Attribute

In HTML class Attribute is used to group elements so they can be styled with CSS or manipulated with JavaScript.

It is one of the most important attributes in HTML.

 1. What Is the class Attribute?

  • Used to assign one or more class names to an element

  • Same class can be used on multiple elements

  • Mostly used with CSS and JavaScript

<p class="text">Hello World</p>

 2. Basic Example

HTML

CSS

  •  Both paragraphs get the same style
  •  One class → many elements

 3. Using class with <div>

 4. Multiple Classes on One Element

You can apply more than one class to a single element.

  •  Classes are separated by space
  •  All styles are applied together

 5. class Selector in CSS

CSS uses dot (.) for class selectors.

 6. class vs id (Very Important)

Featureclassid
UniqueNoYes
ReusableYesNo
CSS selector.class#id
JS usageCommonVery specific
  •  Use class for styling groups
  •  Use id for unique elements

 7. Using class in JavaScript (Intro)


 

  •  Selects all elements with class note

 8. Naming Rules & Best Practices

  •  Class names are case-sensitive
  •  Use meaningful names (btn-primary, header, card)
  • Avoid spaces (use hyphen -)
  • One word or kebab-case preferred

 Bad:

<p class="red text big">

 Good:

<p class="text-large text-danger">

Common Mistakes

  •  Using same id instead of class 
  •  Forgetting dot (.) in CSS
  •  Using spaces instead of hyphens
  •  Overusing too many classes unnecessarily

 Key Points to Remember

  • class is use to style and group elements

  • Multiple elements can share same class

  • Multiple classes can be applied to one element

  • Selected using . in CSS

  • Very important for CSS & JS

You may also like...