HTML Classes


🔹 What is a Class in HTML?

In HTML, the class attribute is used to assign one or more names (called classes) to an element. These class names can be targeted in CSS and JavaScript to apply styles or behaviors.

It allows grouping of elements with similar characteristics or purposes.


🔹 Basic Syntax
<tag class="className">Content</tag>

You can assign multiple class names separated by spaces:

<div class="box red large">Example</div>

🔹 Why Use Classes?

  • To apply CSS styles to multiple elements

  • To select elements using JavaScript

  • To reuse design patterns easily

  • To control layout with consistency


🔹 Example: Using Class with CSS
<style>
  .highlight {
    background-color: yellow;
    font-weight: bold;
  }
</style>

<p class="highlight">This text is highlighted.</p>

🔹 Multiple Elements, Same Class

<div class="card">Card 1</div>
<div class="card">Card 2</div>

Both cards can be styled at once:

.card {
  border: 1px solid #ccc;
  padding: 10px;
}

🔹 Multiple Classes on One Element

<p class="text bold italic">This is styled text</p>
.text { font-size: 16px; }
.bold { font-weight: bold; }
.italic { font-style: italic; }

🔹 Selecting Classes in JavaScript

<button class="btn" onclick="changeText()">Click Me</button>
<p class="msg">Hello!</p>

<script>
  function changeText() {
    document.querySelector('.msg').innerText = "Text changed!";
  }
</script>

Practice Questions

Q1. Create a paragraph with a class that changes text color to blue.

Q2. Add a box class to a <div> and apply border and padding.

Q3. Style multiple <p> elements using the same class.

Q4. Apply two different classes (red, bold) to a heading.

Q5. Target a class in JavaScript to change its content.

Q6. Create a card layout using .card and .card-title classes.

Q7. Use CSS to style a class .warning with red text and border.

Q8. Add a class to a <ul> and change its bullet style.

Q9. Write a button that toggles a class on click using JavaScript.

Q10. Create a class .centered to center-align any content.


Go Back Top