2.9. Using Classes#
2.9.1. Element Classes#
HTML elements can optionally belong to one or more classes. This is commonly used in combination with element selectors so that you can create differently styled versions of each element. For example, you may want two different heading styles.
Classes are assigned using the class attribute, which can be repeated
throughout the HTML document and even applied to elements of different types.
Here’s an example:
<p class="main-para">This is a paragraph of text.</p>
<p class="quote-para">Talk is cheap. Show me the code.</p>
In the example there are two classes named, applied to different paragraphs:
main-paraquote-para
Rules for Classes:
class names are case sensitive
2.9.2. Class Selectors#
To select based on class, use a . followed by the class name as the
selector e.g.
.class {
property1: value1;
property2: value2
}
Have a look at the example below.
<html>
<head>
<style>
.coloured{
color: red;
}
.quote {
text-align: center;
font-style: italic;
}
</style>
<head>
<body>
<p class="coloured">
The Lion King came out in 1994 and with it, some of
Disney's most famous songs including
</p>
<p class="quote coloured">"The Circle Of Life"</p>
<p>Arguably, Disney's more recent songs have become even more famous.</p>
<p>One such example is</p>
<p class="quote">"Let It Go"</p>
<p>from Frozen and,</p>
<p class="quote">"We Don't Talk About Bruno"</p>
<p>from Encanto.</p>
</body>
</html>
A few things to note:
Anything in the
colouredclass is redAnything in the
quoteclass is italicised and centredThe phrase “The Circle of Life” is in both the
colouredandquoteclass so it is red, italicised and centred
To limit the class to specific element types place the element type before the
. In the example below only <p> elements with class="quote-para"
will be centre-aligned.
<html></html>
<head>
<style>
p.center{
text-align:center;
}
</style>
<head>
<body>
<h1 class="center">The heading is not centered...</h1>
<p>even though it's in the center class.</p>
<p class="center">
This is because only paragraph elements in the centered class
</p>
<p>will be centerd.</p>
</body>
</html>