-
Hajipur, Bihar, 844101
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.
<tag class="className">Content</tag>
You can assign multiple class names separated by spaces:
<div class="box red large">Example</div>
To apply CSS styles to multiple elements
To select elements using JavaScript
To reuse design patterns easily
To control layout with consistency
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
<p class="highlight">This text is highlighted.</p>
<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;
}
<p class="text bold italic">This is styled text</p>
.text { font-size: 16px; }
.bold { font-weight: bold; }
.italic { font-style: italic; }
<button class="btn" onclick="changeText()">Click Me</button>
<p class="msg">Hello!</p>
<script>
function changeText() {
document.querySelector('.msg').innerText = "Text changed!";
}
</script>
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.
Q1: Which attribute is used to define a class in HTML?
Q2: How do you assign multiple classes to one element?
Q3: What does a class do in HTML?
Q4: Which CSS selector targets a class?
Q5: Which of these class names is valid?
Q6: Which HTML tag can use the class attribute?
Q7: How does JavaScript access a class?
Q8: Can different elements share the same class name?
Q9: Which CSS rule targets elements with class box?
Q10: Can a class be used more than once on a page?