HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

HTML Classes

Imagine you have 100 buttons on your website, and you want them all to be blue with white text. Writing the style="background: blue; color: white;" attribute 100 times is inefficient and hard to maintain. Enter the HTML Class attribute.

The class attribute allows you to assign a specific category name to an HTML element. You can then write your CSS styling once in a stylesheet and target that class name, instantly styling every element on the page that shares it.


Using the Class Attribute

To use a class, you simply add the class attribute to your HTML tag and give it a custom name (e.g., class="city" or class="warning"). In your CSS rules, you target a class by writing a period (.) followed by the class name.

<!-- CSS Stylesheet -->
<style>
.city {
  background-color: tomato;
  color: white;
  border: 2px solid black;
  margin: 10px;
  padding: 10px;
}
</style>

<!-- HTML Document -->
<div class="city">
  <h2>London</h2>
  <p>London is the capital of England.</p>
</div>

<div class="city">
  <h2>Paris</h2>
  <p>Paris is the capital of France.</p>
</div>

London

London is the capital of England.

Paris

Paris is the capital of France.


Multiple Classes

The true power of classes comes from the fact that an HTML element can belong to more than one class at a time. This allows you to mix and match different styles like building blocks.

To combine classes, simply separate the names with a space inside the quotes.

<!-- CSS -->
<style>
.btn {
  padding: 10px 20px;
  border-radius: 5px;
  font-weight: bold;
}
.btn-danger {
  background-color: red;
  color: white;
}
.btn-large {
  font-size: 24px;
}
</style>

<!-- HTML -->
<!-- This button inherits the basic shape, but becomes red and large -->
<button class="btn btn-danger btn-large">Delete Account</button>

Different Tags, Same Class

Classes are incredibly flexible. You do not have to restrict a class name to just one type of HTML element. A heading <h2> and a paragraph <p> can both share the exact same class and receive the exact same styling.

<h2 class="important-text">Attention!</h2>
<p class="important-text">This message is also very important.</p>
JavaScript Target: The class attribute isn't just for CSS. JavaScript developers heavily use classes to quickly grab multiple elements off the page at once (using the document.getElementsByClassName() method or the document.querySelectorAll() method) to trigger animations or functionality.