Hands On: Using an Embedded Style Sheet
In this lesson, we will learn how to use an embedded style sheet in our HTML file. Let's begin!
In the last exercise, you applied the same exact style attribute to three occurrences of <h1>
and six occurrences of <h2>
.
Think it over: What happens if your customer does not like the peach color used in <h2>
? What if they insist on changing peach to light blue? You need to update each style attribute that belongs to an <h2>
element one-by-one.
You can imagine how much effort it would take with long HTML pages, moreover with websites built of several hundred pages!
Yikes! Luckily, we have a solution to that.
A sibling technology, CSS (Cascading Style Sheets), that works in tandem with HTML offers a solution for this issue. At the moment, just take CSS into account as something that describes styles; later you will learn more nitty-gritty details about it.
With CSS you can transform the HTML page describing the book’s table of contents (our HTML code’s output from the previous exercises) into a more maintainable and more easily readable form, as you will learn from the next exercise.
Exercise: Embedding a style sheet into the web page
To convert the style attributes into a style sheet, follow these steps:
Step 1
From index.html remove all style
attributes from the <body>
, <h1>
, and <h2>
tags.
Step 2
Add a style sheet to the section of the HTML page, as highlighted in the following code:
<!DOCTYPE html><html><head><title>Table of Contents</title><style>body {font-family: Verdana, Arial, sans-serif;}h1 {color: white;background-color: #61b3e7;}h2 {color: #FF645F;margin-left: 40px;}</style></head><body ><h1>Introduction</h1><h2>Whom this book is for?</h2><h2>Errata</h2><h1>Chapter 1</h1><h2>What you will learn in this chapter</h2><h2>Summary</h2><h1>Chapter 2</h1><h2>Recap</h2><h2>Conclusion</h2></body></html>
LIVE coding widget
Use our live coding widget below to write your code. As always, we encourage you to type out the code to get better practice.
To get the code up and running simply click the Run
button below
and see the output in action both in the output tab and the host link provided below.
If you make any changes to your code, the live-server will detect these. Just press run as there is no need to restart the server!
<!--Type your HTML5 code here-->
Step 3 #
Display the page via the link given in the live coding widget above.
As you can see, it is exactly the same at the end of the previous exercise as shown below:
Step 4
Change the style of <h2>
by changing the color to light blue and adding a border at the top:
h2 {color: #61b3e7;margin-left: 40px;border-bottom: 4px dotted black;}
Now, as you can see in the browser , the style of the second level headings has changed according to the modified style definition.
In the next lesson, we’ll understand the workings of the above exercise.
See you there! :)