Home | SkillForge Blog | How to create a class in HTML and CSS

How to create a class in HTML and CSS

CSS, HTML5, Web Design

In CSS you need to be able to select something on the HTML page to be able to style it.  Let’s take this HTML page for example:

<!DOCTYPE html>
<html lang=””>
<head>
<meta charset=”utf-8″>
<title></title>
</head>
<body>
<div>Style Me</div>
</body>
</html>

On that page, we have a <div> that we want to style.  We want to turn the text red.  To do that we need to place a class on the div tag like so:

<div class=”colorMe”>Style Me</div>

We added the class of “colorMe” to this div so now we can select it and style it.  There are many ways to do this but one way is to use internal styling by placing an opening and closing <style> tag inside of the <head> tag like so:

<head>
<meta charset=”utf-8″>
<style>

</style>
<title></title>
</head>

Now that we have the style tag in there we can use the class we created to color the text red.  We use a period to define that we are selecting a class.  It looks like this:

<style>
.colorMe{

color:red;

}
</style>

The .colorMe is called the selector, it is selecting the tag on the page that has the class of colorMe.  Inside the curly brackets, we are defining what we are going to do to that div.  Color is the property and red is the value of that property.  So, in the end, we are selecting the div with the class of colorMe and changing it’s color to red.  Here’s the completed code:

<!DOCTYPE html>
<html lang=””>
<head>
<meta charset=”utf-8″>
<title></title>
<style>
.colorMe{
color:red;
}
</style>
</head>

<body>
<div class=”colorMe”>Style Me</div>
</body>
</html>

If you want to learn more about CSS be sure to check out our HTML/CSS/JavaScript training.  Have an amazing day!