Author: MDBootstrap
Using the class
Attribute
The HTML class
attribute is used to define equal styles for elements with
the same class name.
So, all HTML elements with the same class
attribute will have the same
format and style.
Here we have three <div>
elements that point to the same class
name:
Note: We will learn more about styling in the CSS tutorial, so don't worry if something from this topic isn't clear right now.
<style>
.cities {
background-color: black;
color: white;
margin: 20px;
padding: 20px;
}
</style>
<div class="cities">
<h2>London</h2>
<p>London is the capital of England.</p>
</div>
<div class="cities">
<h2>Paris</h2>
<p>Paris is the capital of France.</p>
</div>
<div class="cities">
<h2>Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>
</div>
Live preview
London
London is the capital of England.
Paris
Paris is the capital of France.
Tokyo
Tokyo is the capital of Japan.
Using the id
Attribute
The id
attribute specifies a unique id for an HTML element (the value
must be unique within the HTML document).
The id value can be used by CSS and JavaScript to perform certain tasks for a unique element with the specified id value.
In CSS, to select an element with a specific id, write a hash (#) character, followed by the id of the element:
Example
Use CSS to style an element with the id myHeader
:
<style>
#myHeader {
background-color: lightblue;
color: black;
padding: 40px;
text-align: center;
}
</style>
<h1 id="myHeader">My Header</h1>
Live preview
My Header
Difference Between Class and ID
An HTML element can only have one unique id that belongs to that single element, while a class name can be used by multiple elements:
<style>
/* Style the element with the id "myHeader" */
#myHeader {
background-color: lightblue;
color: black;
padding: 40px;
text-align: center;
}
/* Style all elements with the class name "city" */
.city {
background-color: tomato;
color: white;
padding: 10px;
}
</style>
<!-- A unique element -->
<h1 id="myHeader">My Cities</h1>
<!-- Multiple similar elements -->
<h2 class="city">London</h2>
<p>London is the capital of England.</p>
<h2 class="city">Paris</h2>
<p>Paris is the capital of France.</p>
<h2 class="city">Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>
Live preview
My Cities
London
London is the capital of England.
Paris
Paris is the capital of France.
Tokyo
Tokyo is the capital of Japan.
Remember: Only one element in your project can have a particular ID.
Remember 2: The same classes can be used by multiple elements.
Previous lesson Next lesson
Spread the word: