Now that we’ve added the content for our pages and blocked out the basic structure, we’re ready to add some styling. Our basic approach involves adding inline styles, which means putting styling commands directly inside the site’s HTML tags. This approach will allow us to understand exactly what our styling is doing on a per-element basis, giving us immediate results.
Inline styles are generally considered a bad practice, though (Box 4.1). En route to fixing this issue, we’ll get just a tiny taste of Cascading Style Sheets—the design language of the Web—by converting inline styles for one of our pages to CSS. This in turn will provide an essential foundation for front-end design and development (Part II) and for writing interactive websites using JavaScript (Learn Enough JavaScript to Be Dangerous (https://www.learnenough.com/javascript)).
As mentioned in Section 3.3, our design efforts will focus on the Moby-Dick book report page, which stands to gain the most from changing the default HTML styling. We’ll begin by adding a little styling to the quotation from the first paragraph of Moby-Dick. Recall from Listing 3.7 that the quotation uses the blockquote
tag, which is set apart from the surrounding text by extra space and indentation (Figure 4.1).
To make the quotation stand out even more, let’s change the font style to italics while increasing the font size to 20 pixels (20px
). The way to do this is with the style
attribute, which can be added to virtually any HTML tag. In this case, we’ll change the font-style
and the font-size
as follows:
style="font-style: italic; font-size: 20px;"
Note that the styling rules after style=
are a single string of characters, with each individual style separated from the others by a semicolon ;
. (The final semicolon isn’t technically necessary, but including it is a good practice since it lets us add additional styles later on without having to remember to add a semicolon.)
Taking this idea and editing moby_dick.html
leads to the HTML shown in Listing 4.1. The result appears in Figure 4.2.
Listing 4.1: Styling the blockquote.moby_dick.html
<blockquote style="font-style: italic; font-size: 20px;">
Next, we’ll add some styling to the famous first line “Call me Ishmael.” We’ll first revert the font style back to normal (which is how you emphasize text when the surrounding text is already in italics). Then we’ll make the font even bigger than the 20px
used for the rest of the quotation, while also making it bold. Finally, we’ll change the color to an attention-grabbing red.
Ordinarily, there would be no way to style just the line “Call me Ishmael.” If we had written it as
Call me Ishmael. Some years ago…
at this point we’d be out of luck. Recall from Listing 3.7, though, that the opening line is wrapped in a span
tag:
<span>Call me Ishmael.</span> Some years ago…
The reason for this is that we correctly anticipated wanting to style it later on. (In practice we can’t always anticipate such things, but of course we can wrap the relevant text in a span
tag as needed.)
Although the span
tag doesn’t really do anything by itself, we can add styles to it, as follows:
<span style="font-style: normal; font-size: 24px; font-weight: bold; color: #ff0000;">Call me Ishmael.</span>
Here we’ve combined font-style
, font-size
, font-weight
, and color
to obtain the results outlined above. These are but a few of the many style properties available, which you can learn about at sites like w3schools (https://www.w3schools.com/cssref/). Meanwhile, the color ff0000
is a hexadecimal code for red, as discussed in Box 4.2.
Including the styles above in moby_dick.html
gives us the code in Listing 4.2, with the result shown in Figure 4.3.
Listing 4.2: Adding style to the opening span
.moby_dick.html
<blockquote style="font-style: italic; font-size: 20px;"> <p> <span style="font-style: normal; font-size: 24px; font-weight: bold; color: #ff0000;">Call me Ishmael.</span> Some years ago–never mind how long precisely–having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world. It is a way I have of driving off the spleen and regulating the circulation. </p> </blockquote>
As a final change, we’ll align the text of the book report headers so that it’s centered in the page. The way to do this is with the text-align
property, as shown in Listing 4.3. (Note that Listing 4.3 also removes the comment from Listing 3.7 since it’s now obsolete.)
Listing 4.3: Centering the headings.moby_dick.html
<header> <h1 style="text-align: center;">A Softcover Book Report</h1> <h2 style="text-align: center;">Moby-Dick (or, The Whale)</h2> </header>
The result appears in Figure 4.4.
Verify that color: red;
has the same effect as color: #ff0000;
. What are the advantages of each approach?
What would you guess the color of #cccccc
is? Temporarily modify the color of the span
in Listing 4.2 to check your guess. How does it differ from #ccc
?
Now that we’ve learned how to move text around, let’s look at how to adjust the placement of other elements. We’ll start by shrinking the size of the cover image down a little, and then we’ll arrange for the text to flow around it as if it were part of the paragraphs and blockquote.
We’ll start by adding the height
attribute to the img
tag to restrict the height to 200 pixels:
<img src="images/moby_dick.png" alt="Moby Dick" height="200px">
Several caveats are in order here. First, although inline resizing is still fairly common, using CSS is the best practice. Second, resizing the image this way (whether inline or with CSS) affects only the image display, and the entire image still needs to be downloaded from the web server, so this technique should be used only for fairly minor resizings.1 (If you’ve ever visited a web page where a seemingly tiny image takes forever to load, this is probably the reason why.) Finally, if you go this route you should use either height
or width
, but not both, as the combination forces the browser to attempt to respect both numbers, which can result in weird image-resizing effects (Figure 4.5).
1. If you need to resize the image itself and don’t have access to Photoshop, you can use the free Skitch (https://evernote.com/products/skitch) utility for resizing, cropping, and simple annotation.
In order to get the text to flow around the image, we need to use a style technique called floating. The idea is that when you set an element to “float” to the left or right (there is no center), all the inline content around it will flow around the floated element. To see this in action, all we need to do is add style=”float: left;”
to the image attributes:
<img src="images/moby_dick.png" alt="Moby Dick" height="200px" style="float: left;">
Inserting this into the book report page gives Listing 4.4, with the result shown in Figure 4.6.
Listing 4.4: Resizing and floating an image.moby_dick.html
<h3>Moby-Dick: A classic tale of the sea</h3> <a href="https://www.softcover.io/read/6070fb03/moby-dick" target="_blank" rel="noopener"> <img src="images/moby_dick.png" alt="Moby Dick" height="200px" style="float: left;"> </a>
In Figure 4.6, the image is effectively treated like text, with the normal text now flowing up and to its side. We’ll see in Section 4.5 that the float
attribute also arranges for the text to flow past the image as well.
What happens if you change float: left
to float: right
in Listing 4.4?
Even though we’ve floated the image, the page still looks a little weird, with the text smashed up against the book cover. To make it look better, we’ll add a margin of empty space to the right of the image.
Margins are one of three styles that can be applied to the imaginary boxes that contain HTML content, the others being padding (empty space inside the box) and borders (a line around the box). We’ll talk more about these styles in the context of the box model covered in Chapter 8 of Part II, but we can accomplish our immediate goal by applying a margin using inline styling. (We’ll see an example of padding in Section 4.5.)
We’ll start with the simplest kind of margin declaration, which looks like margin: 40px;
:
<img src="images/moby_dick.png" alt="Moby Dick" height="200px" style="float: left; margin: 40px;">
If we add this to the img
tag (Listing 4.5), everything surrounding the image moves 40 pixels in each direction, as shown in Figure 4.7.
Listing 4.5: Adding an image margin.moby_dick.html
<h3>Moby-Dick: A classic tale of the sea</h3> <a href="https://www.softcover.io/read/6070fb03/moby-dick" target="_blank" rel="noopener"> <img src="images/moby_dick.png" alt="Moby Dick" height="200px" style="float: left; margin: 40px;"> </a>
Figure 4.7 shows that we’ve gotten closer to our goal by putting some space between the text and the image, but the styling still isn’t quite what we want. The reason is that writing margin: 40px;
applies the margin in all directions, but we really only want the margin on the right side of the image, to separate it from the text.
The most general way to control where the margin goes is to give the margin
attribute four values, corresponding to the top, right, bottom, and left of the box (Figure 4.8).
For example, to get margins of 40, 30, 20, and 10 pixels going around an image (clockwise from the top), we could use this style
attribute:
<img src="…" style="margin: 40px 30px 20px 10px;">
In the present case, we want only a right margin, so we can set the other three sides to 0px
(or just 0
for short):2
2. We could use the attribute style="margin-right: 40px;"
to achieve the same effect, but specifying all four margins is the dominant convention and so is worth learning.
<img src="images/moby_dick.png" alt="Moby Dick" height="200px" style="float: left; margin: 0 40px 0 0;">
Applying this to the full source of the book report page gives Listing 4.6.
Listing 4.6: Adding only a right margin.moby_dick.html
<h3>Moby-Dick: A classic tale of the sea</h3> <a href="https://www.softcover.io/read/6070fb03/moby-dick" target="_blank" rel="noopener"> <img src="images/moby_dick.png" alt="Moby Dick" height="200px" style="float: left; margin: 0 40px 0 0;"> </a>
The result of Listing 4.6 shows exactly the result we want, with a margin applied only on the right, as seen in Figure 4.9.
How does the margin in Listing 4.6 change if we replace the margin with margin-right: 40px
?
Add the style rule padding: 10px;
to the td
elements for the first two block elements in the table in tags.html
. How annoying would it be to add them to every td
? How annoying is it to change from 10px
to 20px
everywhere? (This is one reason why in real life you always use CSS.)
There are a couple more margin tricks worth mentioning, both of which we can immediately put to good use. First, in addition to the shorthand margin: 40px
(with only one value), it’s possible to include only two values:
margin: 20px 40px;
As illustrated in Figure 4.8, this syntax sets the top and bottom margins to 20px
and the left and right margins to 40px
, so it is equivalent to
margin: 20px 40px 20px 40px;
This shorthand also works with just three values, like this: margin: 20px 10px 40px;
. This is missing the last value, which (as seen in Figure 4.8) is the left margin. In this case, it will be filled in automatically from its opposite across the box (in this case, 10px
).
We can apply this to the header for the book report page by adding a bottom margin via margin: 0 0 80px
, as shown in Listing 4.7.
Listing 4.7: Centering the book report headers.moby_dick.html
<header style="text-align: center; margin: 0 0 80px;"> <h1>A Softcover Book Report</h1> <h2>Moby-Dick (or, The Whale)</h2> </header>
Note that we’ve also taken this opportunity to hoist the style text-align: center
into the header
tag. The result appears in Figure 4.10.
The second margin trick is the use of auto
, which inserts a margin with a size that is automatically the same on all relevant sides. Its most common application is probably in the rule
margin: 0 auto;
which arranges for no top or bottom margin and for automatic margins on the left and right. The result of equal left and right margins is that the element is centered, which is especially useful for elements like images that can’t be centered using the text-align: center;
rule we saw in Listing 4.3.
One restriction of margin: 0 auto;
is that it works only on block elements, but recall from Box 3.1 that the img
tag is an inline element. We can fix this with the style display: block;
, which overrides the default. Putting this together with the margin rule leads to Listing 4.8, with the result shown in Figure 4.11.
Listing 4.8: A centered image.moby_dick.html
<a href="https://commons.wikimedia.org/wiki/File:Sperm_whale_pod.jpg"> <img src="images/sperm_whales.jpg" style="display: block; margin: 0 auto;"> </a>
What happens if you use margin: 0 auto;
for the book cover image (together with display: block;
) without changing the float rule? What does this tell you about the precedence of the two rules?
So far, the changes we’ve made have had a relatively minor impact on the appearance of the book report page. In this section, we’ll see how a set of only four style rules can make a surprisingly big difference.
Recall from Listing 3.7 that we wrapped the bulk of the report in a div
tag, which defines a block element that doesn’t get any default styling from the browser, thereby making it perfect to use as a wrapper for styling other content. In this case, we’ll use the width
style to restrict the size of the main report to 500 pixels, and it turns out this lets us use the automatic margin trick from Section 4.4 to center it using margin: 20px auto;
(thereby also putting a 20-pixel margin on the top and bottom). Finally, we’ll combine a padding
rule with a change in the background-color
using the hexadecimal color convention covered in Box 4.2. The resulting style rules appear in Listing 4.9.
Listing 4.9: Adding styling to the book report box.moby_dick.html
<div style="width: 500px; margin: 20px auto; padding: 30px; background-color: #fafafa;"> <h3>Moby-Dick: A classic tale of the sea</h3>
Comparing the before and after (Figure 4.12) shows what a difference a few style rules can make.
As we see in Figure 4.12, the report content has now been set apart from the rest of the page in a styled box.
To recap what happened, we set a width for the box, and because of this we were able to set the left and right margins to auto
. Then we added padding to the box, which pushed the content inside away from the edges. (Investigating the difference between padding and margins is left as an exercise (Section 4.5.1).) We also added a light gray background color with the hexadecimal code #fafafa
(Box 4.2). (Don’t worry about trying to visualize the color corresponding to a hex code; that’s what color pickers are for.) Finally, because of the narrower width, the text of the Moby-Dick quotation now flows around the floated cover image, thereby fulfilling the promise made at the end of Section 4.2.
Temporarily change padding
to margin
in Listing 4.9. What difference does this make in the appearance?
Add and style a blockquote with padding and a background color as shown in Listing 4.10. Fill in TAG
with the right level tag for that location in the document, and replace FILL_IN
with a reasonable color of your choice. The result for one color choice appears in Figure 4.13.
Listing 4.10: Styling a famous quotation.index.html
<h1>The Learn Enough Story</h1> . . . <img src="images/kitten.jpg" alt="An adorable kitten"> <TAG>Quotations</TAG> <p> In addition to hosting most of the world's supply of kitten videos, the Web is also full of inspiring quotes, perhaps none more so than this one: </p> <blockquote style="padding: 2px 20px; background: #FILL_IN;"> <p> <em>Don't believe every quote you read on the Internet.</em> <br> —Abraham Lincoln </p> </blockquote>
As a final change to our sample website, we’ll make a change across all three pages by adding styling to the navigation menu added in Section 3.5. In the process, we’ll yet again feel the pain of having to make the same change in several places, further preparing us to appreciate the value of the template system developed in Part II.
To style the nav menu, we’ll first move it from the top left of the page to the more conventional top right. This will involve adding a style rule to the div
tag that wraps the whole menu (Listing 3.9). At the same time, we’ll add a left margin to the second and third nav links in order to improve the spacing. The changes to the book report page appear in Listing 4.11, and the result appears in Figure 4.14.
Listing 4.11: Styling the navigation menu on the book report page.moby_dick.html
<div style="text-align: right;"> <a href="index.html">Home</a> <a href="tags.html" style="margin: 0 0 0 10px;">HTML Tags</a> <a href="moby_dick.html" style="margin: 0 0 0 10px;">Moby Dick</a> </div>
Of course, we’re not done yet, as we need to make the same edits to the nav menu on the Home page (Listing 4.12) and HTML Tags page (Listing 4.13).
Listing 4.12: Styling the navigation menu on the Home page.index.html
<div style="text-align: right;"> <a href="index.html">Home</a> <a href="tags.html" style="margin: 0 0 0 10px;">HTML Tags</a> <a href="moby_dick.html" style="margin: 0 0 0 10px;">Moby Dick</a> </div>
Listing 4.13: Styling the navigation menu on the HTML Tags page.tags.html
<div style="text-align: right;"> <a href="index.html">Home</a> <a href="tags.html" style="margin: 0 0 0 10px;">HTML Tags</a> <a href="moby_dick.html" style="margin: 0 0 0 10px;">Moby Dick</a> </div>
The results on the nav menu are exactly the same as shown in Figure 4.14. This is not surprising given that the changes represented by Listing 4.11, Listing 4.12, and Listing 4.13 are all identical. This sort of repetition is cumbersome and error-prone— definitely a Bad Thing. As mentioned several times before, we’ll solve this problem with a templating system in Part II.
Change margin: 0 0 0 10px;
to margin-left: 10px;
in Listing 4.13. What, if anything, changes in the appearance?
It’s conventional for navigation links not to change color after being followed, and they also look better if they’re not underlined like normal links. Using your Google-fu and the w3schools reference, guess the style rules for making these changes, and apply them to each element in the menu. Hint: The property you’ll have to modify to remove underlining is text-decoration
. The result should look something like Figure 4.15.
Add a new table for the “document tags” that define the properties of the document. Include html
, head
, body
, title
, and meta
.
Add any missing tags to tags.html
. (By our count there are five, after including the tags from the previous exercise.)
In this section, we’ll get a first taste of Cascading Style Sheets (CSS),3 using the inline styles from index.html
as our example. We’ll break the transition from inline styles to CSS into two steps: First, we’ll move the inline styles into an internal stylesheet (Section 4.7.1); second, we’ll move the internal style rules into an external stylesheet (Section 4.7.2). The result will be a self-contained and centralized location for our page’s styling.
3. The words “style” and “sheet” are conventionally written as two words—Style Sheet—only in the context of spelling out the meaning of “CSS”. Otherwise, they are generally combined into one word, “stylesheet”.
We’ll start by refactoring the inline styles into an internal stylesheet. Refactoring involves changing the form of code or markup without changing its function. In this case, we’ll be moving the style rules on the elements in index.html
into the head
of our document, using a special style
tag designed for exactly this purpose. In preparation for this, we’ll add the opening and closing style
tags with empty space for the style rules, as shown in Listing 4.14.
Listing 4.14: Adding an empty style
tag (to be filled in in this section).index.html
<!DOCTYPE html> <html> <head> <title>Learn Enough to Be Dangerous</title> <meta charset="UTF-8"> <style> </style> </head>
Our first step is to move the navigation styling developed in Section 4.6 (Listing 4.12). Two of the lines contain identical margin styles: margin: 0 0 0 10px
(which control the spacing between links). To eliminate this repetition, we’ll start by replacing each of the inline styles with one of the most important ideas in web design, a CSS class, as shown in Listing 4.15.
Listing 4.15: Replacing the inline style with a CSS class.index.html
<div style="text-align: right;"> <a href="index.html">Home</a> <a href="tags.html" class="nav-spacing">HTML Tags</a> <a href="moby_dick.html" class="nav-spacing">Moby Dick</a> </div>
A CSS class acts as a named label for the element, and allows us to simultaneously style all elements with the given class. The code for doing this involves the name of the class with a leading dot (.nav-spacing
) and a list of style rules (in this case, only one) inside curly braces. In order to apply the styling to the page, this code should be placed inside the style
tag, as shown in Listing 4.16.
Listing 4.16: Moving the inline margin
rule into an internal stylesheet.index.html
<style> .nav-spacing { margin: 0 0 0 10px; } </style>
Note that the margin
rule in Listing 4.16 is identical to the one we used inline; this is a general pattern for inline styles and CSS.
Next, we’ll replace the inline style for the navigation div
with another CSS class (Listing 4.17) and a second CSS rule (Listing 4.18).
Listing 4.17: Replacing the inline style with a class.index.html
<div class="nav-menu"> <a href="index.html">Home</a> <a href="tags.html" class="nav-spacing">HTML Tags</a> <a href="moby_dick.html" class="nav-spacing">Moby Dick</a> </div>
Listing 4.18: Adding the nav menu rule to the internal stylesheet.index.html
<style> .nav-menu { text-align: right; } .nav-spacing { margin: 0 0 0 10px; } </style>
Here we’ve placed the .nav-menu
rule above the .nav-spacing
rule, but in this case the order doesn’t matter. (The order of CSS rules often does matter, though; the details are covered in Part II.)
As a final step, we’ll add the counterpart to a CSS class, called a CSS “identifier”, or id (read as separate letters: “eye-dee”). Adding an id is certainly not necessary, nor is it considered a good practice to use ids for styling (for reasons covered in Part II); we include it here mainly for purposes of illustration. But ids can be quite useful for deep linking (discussed in Section 4.7.3), and they are essential for many JavaScript applications (as covered in Learn Enough JavaScript to Be Dangerous).
In this case, we’ll call the id main-nav
(to indicate the main navigational element) and add it to the main navigational div
, as shown in Listing 4.19. This has no effect on the page’s appearance but serves to illustrate the syntax. Note that, unlike classes, which can be used multiple times on a page, a given CSS id can be used only once.
Listing 4.19: Adding a CSS id.index.html
<div id="main-nav" class="nav-menu"> <a href="index.html">Home</a> <a href="tags.html" class="nav-spacing">HTML Tags</a> <a href="moby_dick.html" class="nav-spacing">Moby Dick</a> </div>
At this point, if you’ve done everything right, the styles should be exactly the same as before, so upon refreshing the browser the appearance of the page should also be the same as it was before we started.
Now that we’ve refactored the inline styles into an internal stylesheet, putting them in an external stylesheet is easy. All we need to do is create a CSS file (which we’ll call main.css
), move the styles there, and then link to the file in the head
of our document.
By convention, CSS files are usually located in a directory called css
or stylesheets
; we’ll pick the former for brevity:
$ mkdir css $ touch css/main.css
All that’s needed now is to cut the CSS rules from index.html
(don’t include the <style>
tags though) and paste them into main.css
(Listing 4.20).
Listing 4.20: The style rules in an external stylesheet.css/main.css
.nav-menu { text-align: right; } .nav-spacing { margin: 0 0 0 10px; }
Finally, we’ll delete the <style></style>
tags and replace them with a link
tag that includes the stylesheet into the page, as shown in Listing 4.21. (The rel
in Listing 4.21 stands for “relationship”; in our experience, it has never been important to know this.)
Listing 4.21: Including the external stylesheet.index.html
<!DOCTYPE html> <html> <head> <title>Learn Enough to Be Dangerous</title> <meta charset="UTF-8"> <link rel="stylesheet" href="css/main.css"> </head>
Putting styles in an external stylesheet is the technique that is generally used in real websites.
As before, moving the CSS into an external stylesheet should have changed nothing about the rules being applied, so the resulting page should look exactly the same as before!
The final step is to make a Git commit (taking care to run git add
since we’ve added a new file and directory):
$ git add -A $ git commit -m "Refactor inline styles into a stylesheet"
With that, we’re done with our brief overview of CSS. This background is (barely) sufficient to skip to a beginning programming tutorial like Learn Enough JavaScript to Be Dangerous, although we recommend solidifying your knowledge by following Part II of this book, which also covers how to use a professional-grade static site generator with a proper templating system to prevent repeated use of code.
If you followed the exercises in Section 2.4.2, there is an image link to the Learn Enough Twitter account that has an inline style to remove underlining, as shown in Listing 2.14. Add a sensible class to this element (such as ”image-link”
) and move the corresponding style rule into main.css
. Does the page remain unchanged as required?
The updated menu shown in Listing 4.17 appears only on the Home page; to fix this, propagate the changes to the other two pages. (Appreciate once again how cumbersome this is and how nice it would be to have a proper templating system.)
Move the style rules for the HTML Tags page and the Moby Dick page into main.css
and confirm that the appearance of the pages stays the same.
One of the simplest and most useful applications of CSS ids is for creating links to arbitrary HTML elements using a convenient hash symbol (#) syntax. By adding the id founders
to the “Founders” h2
tag (Listing 4.22), show that you can visit that section of the page directly by pasting the URL sample_website/index.html#founders into your browser’s address bar.
Listing 4.22: Adding a CSS id for deep linking.index.html
<h2 id="founders">Founders</h2>
Congratulations! You now know enough HTML to be dangerous. All that’s left is to commit (in case you’ve made changes in Section 4.7.3) and deploy the final sample website:
$ git commit -am "Finish the sample website" $ git push
The result is a full website running in a production environment (Figure 4.16).
For reference, summary tables of all the block-level tags and inline tags appear in Table 4.1 and Table 4.2, respectively.
Table 4.1: The block-level tags covered in this tutorial.
Tag | Name | Purpose |
---|---|---|
| Headings | Include a heading (levels 1–6) |
| Paragraph | Include a paragraph of text |
| Table | Include a table |
| Table row | Include a row of data |
| Table header | Make a table header |
| Table data | Include a table data cell |
| Division | Define block-level section in document |
| Header | Label the page header |
| Ordered list | List elements in numerical order |
| Unordered list | List elements whose order doesn’t matter |
| List item | Include a list item (ordered or unordered) |
| Block quotation | Show formatted quotation |
| Break | Enter line break |
Table 4.2: The inline tags covered in this tutorial.
Tag | Name | Purpose | Example | Result |
---|---|---|---|---|
| Emphasized | Make emphasized text |
| technical sophistication |
| Strong | Make strong text |
| at least a billion people |
| Anchor | Make hyperlink |
| Learn Enough |
| Image | Include an image |
| |
| Code | Format as source code |
| table |
| Span | Define inline section in document |
| Call me Ishmael. |
At this point, you’ve got a solid foundation in the basics of HTML. This means you have the perfect preparation for learning how to make a professional-grade website with attractive styling and fancy page layouts. In other words, you’re now ready for Part II!
3.142.98.186