Lesson 3

Understanding Cascading Style Sheets

What You'll Learn in This Lesson:

  • Image How to create a basic style sheet

  • Image How to use style classes

  • Image How to use style IDs

  • Image How to construct internal style sheets and inline styles

In the preceding lesson, you learned the basics of HTML, including how to set up a basic HTML template for all your web content. In this lesson, you’ll learn how to fine-tune the display of your web content by using Cascading Style Sheets (CSS).

The concept behind style sheets is simple: You create a style sheet document that specifies the fonts, colors, spacing, and other characteristics that establish a unique look for a website. You then link every page that should have that look to the style sheet instead of specifying all those styles repeatedly in each separate document. Then, when you decide to change your official corporate typeface or color scheme, you can modify all your web pages at once just by changing one or two entries in your style sheet; you don’t have to change them in all your static web files. So, a style sheet is a grouping of formatting instructions that control the appearance of several HTML pages at once.

Style sheets enable you to set a great number of formatting characteristics, including exact typeface controls, letter and line spacing, and margins and page borders, to name just a few. Style sheets also enable you to specify sizes and other measurements in familiar units, such as inches, millimeters, points, and picas. In addition, you can use style sheets to precisely position graphics and text anywhere on a web page, either at specific coordinates or relative to other items on the page.

In short, style sheets bring a sophisticated level of display to the Web. And they do so, if you’ll pardon the expression, with style.

How CSS Works

The technology behind style sheets is called CSS, or Cascading Style Sheets. CSS is a language that defines style constructs such as fonts, colors, and positioning, which describe how information on a web page is formatted and displayed. CSS styles can be stored directly in an HTML web page or in a separate style sheet file. Either way, style sheets contain style rules that apply styles to elements of a given type. When used externally, style sheet rules are placed in an external style sheet document with the file extension .css.

A style rule is a formatting instruction that can be applied to an element on a web page, such as a paragraph of text or a link. A style rule consists of one or more style properties and their associated values. An internal style sheet is placed directly within a web page, whereas an external style sheet exists in a separate document and is linked to a web page via a special tag; you’ll learn more about this tag in a moment.

The cascading part of the name CSS refers to the manner in which style sheet rules are applied to elements in an HTML document. More specifically, styles in a CSS style sheet form a hierarchy in which more specific styles override more general styles. It is the responsibility of CSS to determine the precedence of style rules according to this hierarchy, which establishes a cascading effect. If that sounds a bit confusing, just think of the cascading mechanism in CSS as being similar to genetic inheritance, in which general traits are passed from parents to a child, but more specific traits are entirely unique to the child. Base style rules are applied throughout a style sheet but can be overridden by more specific style rules.

Note

You might notice that we use the term element a fair amount in this lesson (and we also do in the rest of the course). An element is simply a piece of information (content) in a web page, such as an image, a paragraph, or a link. Tags are used to mark up elements, and you can think of an element as a tag, complete with descriptive information (attributes, text, images, and so on) within the tag.

A quick example should clear things up. Take a look at the following code to see whether you can tell what’s going on with the color of the text:

<div style="color:green;">
  This text is green.
  <p style="color:blue;">This text is blue.</p>
  <p>This text is still green.</p>
</div>

In this example, the color green is applied to the <div> tag via the color style property. Therefore, the text in the <div> tag is colored green. Because both <p> tags are children of the <div> tag, the green text style cascades down to them. However, the first <p> tag overrides the color style and changes it to blue. The end result is that the first line (not surrounded by a paragraph tag) is green, the first official paragraph is blue, and the second official paragraph retains the cascaded green color.

If you made it through that description on your own and came out on the other end unscathed, congratulations—that’s half the battle. Understanding CSS isn’t difficult, and the more you practice, the more it will become clear. The real trick is developing an aesthetic design sense that you can then apply to your online presence through CSS.

Like many other web technologies, CSS has evolved over the years. The original version of CSS, known as Cascading Style Sheets Level 1 (CSS1), was created in 1996. The later CSS2 standard, created in 1998, is still in use today. The latest version of CSS is CSS3, and it builds on the strong foundation laid by its predecessors but adds advanced functionality to enhance the online experience. Modern web browsers support all of CSS2 and a majority of CSS3. Throughout this series of lessons, you’ll learn core CSS, including new elements of CSS3 that are applicable to the basic design and functionality that this text covers. So, when we talk about CSS, we’re referring to CSS3.

You can find a complete reference guide to CSS at www.w3.org/Style/CSS/. The rest of this lesson explains the basics of putting CSS to good use.

A Basic Style Sheet

Despite their intimidating power, style sheets are simple to create. Consider the web pages shown in Figures 3.1 and 3.2. These pages share several visual properties that can be put into a common style sheet:

  • Image They use a large, bold Verdana font for the headings and a normal-size and -weight Verdana font for the body text.

  • Image They use an image named logo.gif floating within the content and on the right side of the page.

  • Image All text is black except for subheadings, which are purple.

  • Image They have margins on the left side and at the top.

  • Image They include vertical space between lines of text.

  • Image They include a footer that is centered and in small print.

A screenshot shows a website named Enjoy Scifi.
Figure 3.1 This page uses a style sheet to fine-tune the appearance and spacing of the text and images.
A screenshot of another page from the Enjoy Scifi website.
Figure 3.2 This page uses the same style sheet as the one in Figure 3.1, thus maintaining a consistent look and feel.

Listing 3.1 shows CSS used in a style sheet to specify these types of properties.

Listing 3.1 A Single External Style Sheet

body {
  font-size: 10pt;
  font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
  color: black;
  line-height: 14pt;
  padding-left: 5pt;
  padding-right: 5pt;
  padding-top: 5pt;
}

h1 {
  font: 14pt Verdana, Geneva, Arial, Helvetica, sans-serif;
  font-weight: bold;
  line-height: 20pt;
}

p.subheader {
  font-weight: bold;
  color: #593d87;
}

img {
  padding: 3pt;
  float: right;
}

a {
  text-decoration: none;
}

a:link, a:visited {
  color: #8094d6;
}

a:hover, a:active {
  color: #FF9933;
}

footer {
  font-size: 9pt;
  font-style: italic;
  line-height: 12pt;
  text-align: center;
  padding-top: 30pt;
}

This might initially appear to be a lot of code, but if you look closely, you’ll see that there isn’t a lot of information on each line of code. It’s fairly standard to place each individual style rule on its own line to help make style sheets more readable, but that is a personal preference; you could put all the rules on one line as long as you kept using the semicolon to separate each rule; you’ll learn more on this in a bit. Speaking of code readability, perhaps the first thing you noticed about this style sheet code is that it doesn’t look anything like normal HTML code. CSS uses a syntax all its own to specify style sheets.

Of course, the listing includes some familiar HTML tags (although not all tags require an entry in the style sheet). As you might guess, body, h1, p, img, a, and footer in the style sheet refer to the corresponding tags in the HTML documents to which the style sheet will be applied. These are called the selectors. The curly braces after each tag name describe how all content within that tag should appear—using the style rules.

In this case, the style sheet says that all body text should be rendered at a size of 10 points, in the Verdana font (if possible), and with the color black, with 14 points between lines. If the user does not have the Verdana font installed, the list of fonts in the style sheet represents the order in which the browser should search for fonts to use: Geneva, then Arial, and then Helvetica. If the user has none of those fonts, the browser uses whatever default sans-serif font is available. In addition, the page should have left, right, and top padding of 5 points each.

Any text within an <h1> tag should be rendered in boldface Verdana at a size of 14 points. Moving on, any paragraph that uses only the <p> tag inherits all the styles indicated by the body element. However, if the <p> tag uses a special class named subheader, the text appears bold and in the color #593d87 (a purple color).

The pt after each measurement in Listing 3.1 means points (there are 72 points in an inch). If you prefer, you can specify any style sheet measurement in inches (in), centimeters (cm), pixels (px), or “widths of a letter m,” which are called ems (em) or rems (rem). There are also units for sizes relative to the width of the number 0 (ch), relative to 1% of the viewport width or height (vw or vh), and relative to the container (%). Length measurements in CSS are defined as fixed or relative. Fixed lengths—such as inches, pixels, or points—do not change size, while relative lengths—such as ems, ch, or percentages—can change.

Note

In CSS, the rem measurement is sized relative to the width of the letter m, but it is relative to the initial font size rather than any changed font sizes that might apply. Best practices recommend that you use relative font sizes (such as rem or em) rather than fixed font sizes (such as inches or points) so that your designs scale more gracefully. Whether you choose rem or em depends mostly on whether you need your type to scale across the whole page (use rem) or you need more explicit control over sections of the document (use em).

You might have noticed that each style rule in the listing ends with a semicolon (;). Semicolons are used to separate style rules from each other. It is therefore customary to end each style rule with a semicolon so that you can easily add another style rule after it. Review the remainder of the style sheet in Listing 3.1 to see the presentation formatting applied to additional tags. Don’t worry: You’ll learn more about each of these types of entries throughout the lessons in this course.

Note

Bear in mind that 10pt is a small font size. Not everyone viewing your page will find such a small font size legible or easy to read. You can specify font sizes as large or small as you like with style sheets, although some older display devices and printers do not correctly handle fonts larger than 200 points. Always test your pages in as many browsers and devices as possible.

To link this style sheet to HTML documents, include a <link> tag in the <head> section of each document. Listing 3.2 shows HTML code for a page that contains the following <link> tag:

<link rel="stylesheet" href="styles.css">

This assumes that the style sheet is stored under the name styles.css in the same folder as the HTML document. As long as the web browser supports style sheets—and all modern browsers do—the properties specified in the style sheet will apply to the content in the page without the need for any special HTML formatting code. This meets one of the goals of HTML, which is to provide a separation between the content in a web page and the specific formatting required to display that content.

Listing 3.2 HTML Code for a Page Using an External Style Sheet

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>About BAWSI</title>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
    <section>
      <header>
        <h1>About BAWSI</h1>
      </header>

      <p><img src="logo.gif" alt="BAWSI logo">The Bay Area Women's
      Sports Initiative (BAWSI) is a public benefit, nonprofit
      corporation with a mission to create programs and
      partnerships through which women athletes bring health, hope
      and wholeness to our community. Founded in 2005 by Olympic
      and World Cup soccer stars Brandi Chastain and Julie Foudy
      and Marlene Bjornsrud, former general manager of the San Jose
      CyberRays women's professional soccer team, BAWSI provides a
      meaningful path for women athletes to become a more visible
      and valued part of the Bay Area sports culture.</p>

     <p class="subheader">BAWSI's History</p>

     <p>The concept of BAWSI was inspired by one of the most
     spectacular achievements in women's sports history and born out
     of one its biggest disappointments...</p>

     <p><a href="secondpage.html">[continue reading]</a></p>
    </section>

    <footer>
      Copyright &copy; 2005-2013 BAWSI (www.bawsi.org).
      All rights reserved.  Used with permission.
    </footer>
  </body>
</html>

Note

In most web browsers, you can view the style rules in a style sheet by right-clicking on the page and choosing Inspect or Inspect Element. There you see the HTML and the specific styles associated with the highlighted element. You can even make temporary edits to see how the page might change. To edit your own style sheets, just use a text editor; most designers use the same editor for CSS that they use for HTML.

The code in Listing 3.2 is interesting because it contains no style formatting of any kind. In other words, nothing in the HTML code dictates how the text and images are to be displayed—no colors, no fonts, nothing. Yet the page is carefully formatted and rendered to the screen, thanks to the link to the external style sheet, styles.css. The real benefit to this approach is that you can easily create a site with multiple pages that maintains a consistent look and feel. And you have the benefit of isolating the visual style of the page to a single document (the style sheet) so that one change impacts all pages.

Note

Not every browser’s support of CSS is flawless. If you want to find out what the support is for a specific CSS property (or HTML tag or other web technology), take a look at the website CanIUse (www.caniuse.com).  

A CSS Style Primer

You now have a basic knowledge of CSS style sheets and how they are based on style rules that describe the appearance of information in web pages. The next few sections of this lesson provide a quick overview of some of the most important style properties and enable you to get started using CSS in your own style sheets.

CSS includes various style properties that are used to control fonts, colors, alignment, and margins, among other things. The style properties in CSS can be generally grouped into two major categories:

  • Image Layout properties—Properties that affect the positioning of elements on a web page, such as margins, padding, and alignment

  • Image Formatting properties—Properties that affect the visual display of elements in a website, such as the font type, size, and color

Basic Layout Properties

CSS layout properties determine how content is placed on a web page. One of the most important layout properties is the display property, which describes how an element is displayed with respect to other elements. The display property has five basic values:

  • Image block—The element is displayed on a new line, as in a new paragraph.

  • Image list-item—The element is displayed on a new line with a list-item mark (bullet) next to it.

  • Image inline—The element is displayed inline with the current paragraph.

  • Image inline-block—The element is displayed as a block-level element inline with surrounding block elements.

  • Image none—The element is not displayed; it is hidden.

Note

The display property relies on a concept known as relative positioning, which means that elements are positioned relative to the location of other elements on a page. CSS also supports absolute positioning, which enables you to place an element at an exact location on a page, independent of other elements. You’ll learn more about both of these types of positioning in Lesson 10, “Understanding the CSS Box Model and Positioning.”

Understanding the display property is easier if you visualize each element on a web page occupying a rectangular area when displayed; the display property controls the manner in which this rectangular area is displayed. For example, the block value results in the element being placed on a new line by itself, whereas the inline value places the element next to the content just before it. The inline-block value treats the element as a block but positions it next to the content just before it, and the img tag is the most commonly used inline-block element. The display property is one of the few style properties that can be applied in most style rules. Following is an example of how to set the display property:

display:block;

Note

The display property has several other values, including table, flex, and grid, and their inline counterparts inline-table, inline-flex, and inline-grid. These values, which offer powerful layout and display functionality, are covered in more detail in Lesson 12, “Creating Layouts Using Modern CSS Techniques.”

You control the dimensions of the rectangular area for an element with the width and height properties. As with many other size-related CSS properties, width and height property values can be specified in several different units of measurement:

  • Image in—Inches

  • Image cm—Centimeters

  • Image em—Ems

  • Image mm—Millimeters

  • Image %—Percentage

  • Image px—Pixels

  • Image pt—Points

  • Image rem—Rems

You can mix and match units any way you like within a style sheet, but it’s generally a good idea to be consistent across a set of similar style properties. For example, you might want to stick with rems for font properties and percentages for dimensions. Following is an example of setting the width of an element using pixel units:

width: 200px;

Basic Formatting Properties

CSS formatting properties are used to control the appearance of content on a web page, as opposed to controlling the physical positioning of the content. One of the most popular formatting properties is the border property, which establishes a visible boundary around an element with a box or partial box. Note that a border is always present in that space is always left for it, but the border does not appear in a way that you can see unless you give it properties that make it visible (such as a color). The following border properties provide a means of describing the borders of an element:

  • Image border-width—The width of the border edge

  • Image border-color—The color of the border edge

  • Image border-style—The style of the border edge

  • Image border-left—The left side of the border

  • Image border-right—The right side of the border

  • Image border-top—The top of the border

  • Image border-bottom—The bottom of the border

  • Image border—All the border sides

The border-width property establishes the width of the border edge. It is often expressed in pixels, as the following code demonstrates:

border-width:5px;

Not surprisingly, the border-color and border-style properties set the border color and style. Following are examples of how these two properties are set:

border-color:blue;
border-style:dotted;

The border-style property can be set to any of the following basic values:

  • Image solid—A single-line border

  • Image double—A double-line border

  • Image dashed—A dashed border

  • Image dotted—A dotted border

  • Image groove—A border with a groove appearance

  • Image ridge—A border with a ridge appearance

  • Image inset—A border with an inset appearance

  • Image outset—A border with an outset appearance

  • Image none—No border

  • Image hidden—Effectively the same as none

You’ll learn about some more advanced border tricks later in this course.

The default value of the border-style property is none, which is why elements don’t have a border unless you set the border-style property to a different style. Although solid is the most common border style, you will also see the other styles in use.

The border-left, border-right, border-top, and border-bottom properties enable you to set the border for each side of an element individually. If you want a border to appear the same on all four sides, you can use the single border property by itself, which expects the following styles, separated by spaces: border-width, border-style, and border-color. Following is an example of using the border property to set a border that consists of two (double) red lines that are a total of 10 pixels in width:

border:10px double red;

You can also adjust the curve of the boxes by changing the border radius with these properties:

  • Image border-top-left-radius—The top-left corner radius

  • Image border-top-right-radius—The top-right corner radius

  • Image border-bottom-left-radius—The bottom-left corner radius

  • Image border-bottom-right-radius—The bottom-right corner radius

  • Image border-radius—The radius for all four corners

The border-radius properties take one or two values. These values define the two radii of a quarter ellipse that describes the shape of the corner. The first value is the horizontal radius and the second the vertical. If there is only one value, it is used for both. This property rounds the corners of both the border and any background placed on the element. Following is an example of using the border-radius property set to 1rem:

border-radius: 1rem;

Whereas the color of an element’s border is set with the border-color property, the color of the inner region of an element is set using the color and background-color properties. The color property sets the color of text in an element (foreground), and the background-color property sets the color of the background behind the text. Following is an example of setting both color properties to predefined colors:

color:black;
background-color:orange;

You can also assign custom colors to these properties by specifying the colors in hexadecimal (covered in more detail in Lesson 8, “Working with Colors, Images, and Multimedia”) or as RGB (red, green, blue) decimal values:

background-color:#999999;
color:rgb(0,0,255);

You can even set the transparency of the colors with the RGBa (red, green, blue, alpha channel) decimal values:

background-color:rgba(0,0,0,0.8);
color:rgba(0,0,255,1.0);

You can also control the alignment and indentation of web page content without too much trouble. This is accomplished with the text-align and text-indent properties, as the following code demonstrates:

text-align:center;
text-indent:12px;

Note

The text-align property applies to the contents of a block-level element, not to the element itself. If you want to center a block element (or an inline-block element, such as an image) you need to use other methods, as discussed in Lesson 9, “Working with Margins, Padding, Alignment, and Floating.”

When you have an element properly aligned and indented, you might be interested in setting its font. The following basic font properties set the various parameters associated with fonts (and you’ll learn about some more advanced font usage in Lesson 6, “Working with Fonts, Text Blocks, Lists, and Tables”):

  • Image font-family—The typeface of the font

  • Image font-size—The size of the font

  • Image font-style—The style of the font (normal or italic)

  • Image font-weight—The weight of the font (normal, lighter, bold, bolder, and so on)

The font-family property specifies a prioritized list of typeface names. A prioritized list is used instead of a single value to provide alternatives in case a font isn’t available on a given system. If the typeface has multiple words, such as “Times New Roman,” you should surround the name with quotation marks. The font-size property specifies the size of the font, using a unit of measurement. Finally, the font-style property sets the style of the font, and the font-weight property sets the weight of the font. Following is an example of setting these font properties:

font-family: Arial, "Gill Sans", sans-serif;
font-size: 1.2rem;
font-style: italic;
font-weight: normal;

Now that you know a whole lot more about style properties and how they work, look at Listing 3.1 again and see whether it makes a bit more sense. Here’s a recap of the style properties used in that style sheet, which you can use as a guide for understanding how it works:

  • Image font—Lets you set many font properties at once. You can specify a list of font names separated by commas; if the first one is not available, the next is tried, and so on. You can also include the words bold and/or italic and a font size. Alternatively, you can set each of these font properties separately with font-family, font-size, font-weight, and font-style.

  • Image line-height—Is also known in the publishing world as leading. This sets the height of each line of text. line-height is usually defined in the same units as font.

  • Image color—Sets the text color using the standard color names or hexadecimal color codes (see Lesson 8 for more details).

  • Image text-decoration—Is useful for turning off link underlining; simply set it to none. The values of underline, overline, and line-through are also supported. Lesson 7, “Using External and Internal Links,” covers applying styles to links in more detail.

  • Image text-align—Aligns text (left, right, or center)  or justifies the text (justify).

  • Image padding—Adds padding to the left, right, top, and bottom of an element; this padding can be in measurement units or a percentage of the page width. Use padding-left and padding-right if you want to add padding to the left and right of the element independently. Use padding-top or padding-bottom to add padding to the top or bottom of the element, as appropriate. You’ll learn more about these style properties in Lessons 9 and 10.

Using Style Classes

This is a “teach yourself” course, so you don’t have to go to a single class to learn how to give your pages great style—although you do need to learn what a style class is. Whenever you want some of the text on your pages to look different from the other text, you can create what amounts to a custom-built HTML tag. Each type of specially formatted text you define is called a style class. A style class is a custom set of formatting specifications that can be applied to any element in a web page.

Before you examine a style class, we need to take a quick step back and clarify some CSS terminology. First, a CSS style property is a specific style to which you can assign a value, such as color or font-size. You associate a style property and its respective value with elements on a web page by using a selector. A selector is used to identify tags on a page to which you apply styles. Following is an example of a selector, a property, and a value all included in a basic style rule:

h1 { font: 36pt Courier; }

In this code, h1 is the selector, font is the style property, and 36pt Courier is the value. The selector is important because it means that the font setting will be applied to all h1 elements in the web page. But what if you want to differentiate between some of the h1 elements? The answer lies in style classes.

Suppose you want two different kinds of <h1> headings for use in your documents. You create a style class for each one by putting the following CSS code in a style sheet:

h1.silly { font: 36pt Comic Sans; }
h1.serious { font: 36pt Arial; }

Notice that these selectors include a period (.) after h1, followed by a descriptive class name. To choose between the two style classes, use the class attribute, like this:

<h1 class="silly">Marvin's Munchies Inc.</h1>
<p>Text about Marvin's Munchies goes here.</p>

Or you could use this:

<h1 class="serious">MMI Investor Information</h1>
<p>Text for business investors goes here.</p>

When referencing a style class in HTML code, simply specify the class name in the class attribute of an element. In the preceding example, the words Marvin's Munchies Inc. would appear in a 36-point Comic Sans font, assuming that you included a <link> to the style sheet at the top of the web page and that the user has the Comic Sans font installed. The words MMI Investor Information would appear in the 36-point Arial font instead. You can see another example of classes in action in Listing 3.2; look for the subheader <p> class.

What if you want to create a style class that can be applied to any element instead of just headings or some other particular tag? In your CSS, simply use a period (.) followed by any style class name you make up and any style rules you choose. That class can specify any number of font, spacing, and margin settings all at once. Wherever you want to apply your custom tag in a page, just use an HTML tag plus the class attribute, followed by the class name you created.

For example, the style sheet in Listing 3.1 includes the following style class specification:

p.subheader {
  font-weight: bold;
  color:#593d87;
}

This style class is applied in Listing 3.2 with the following tag:

<p class="subheader">

Note

You might have noticed a change in the coding style when a style rule includes multiple properties. For style rules with a single style, you commonly see the property placed on the same line as the rule, like this:

p.subheader { font-weight: bold; }

However, when a style rule contains multiple style properties, it’s much easier to read and understand the code if you list the properties one per line, like this:

p.subheader {
  font-weight: bold;
  color:#593d87;
}

Everything between that tag and the closing </p> tag in Listing 3.2 appears in bold purple text.

What makes style classes so valuable is that they isolate style code from web pages, enabling you to focus your HTML code on the actual content in a page rather than on how it is going to appear on the screen. Then you can determine how the content is rendered to the screen by fine-tuning the style sheet. You might be surprised by how a relatively small amount of code in a style sheet can have significant effects across an entire website. Style classes make your pages much easier to maintain and manipulate.

Using Style IDs

When you create custom style classes, you can use those classes as many times as you like; they are not unique. However, in some instances, you want precise control over unique elements for layout or formatting purposes (or both). In such instances, look to IDs instead of classes.

A style ID is a custom set of formatting specifications that can be applied to only one element in a web page. You can use IDs across a set of pages—but only once within each page.

For example, suppose you have a title within the body of all your pages. Each page has only one title, but each page includes one instance of that title. Following is an example of a selector with an ID indicated, plus a property and a value:

p#title {font: 24pt Verdana, Geneva, Arial, sans-serif}

Notice that this selector includes a hash tag, or pound sign (#), after p, followed by a descriptive ID name. When referencing a style ID in HTML code, simply specify the ID name in the id attribute of an element, like so:

<p id="title">Some Title Goes Here</p>

Everything between the opening and closing <p> tags will appear in 24-point Verdana text—but only once on any given page. You often see style IDs used to define specific parts of a page for layout purposes, such as a header area, footer area, main body area, and so on. These types of areas in a page appear only once per page, so using an ID rather than a class is the appropriate choice.

Internal Style Sheets and Inline Styles

In some situations, you want to specify styles that will be used in only one web page. You can enclose a style sheet between <style> and </style> tags and include it directly in an HTML document. Style sheets used in this manner must appear in the <head> of an HTML document. No <link> tag is needed, and you cannot refer to that style sheet from any other page (unless you copy it into the beginning of that document, too). This kind of style sheet is known as an internal style sheet, as you learned earlier in the lesson.

Note

In many web pages, you see the attribute type="text/css" on the <style> tag. This used to be required for valid HTML, but most modern browsers assume that is the type unless otherwise specified. So, in HTML5, that attribute is no longer required.

Listing 3.3 shows an example of how you might specify an internal style sheet.

Listing 3.3 A Web Page with an Internal Style Sheet

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Some Page</title>
    <style>
      footer {
        font-size: 9pt;
        line-height: 12pt;
        text-align: center;
      }
    </style>
  </head>
  <body>
  ...
  <footer>
  Copyright 2018 Acme Products, Inc.
  </footer>
  </body>
</html>

In Listing 3.3, the footer style class is specified in an internal style sheet that appears in the head of the page. The style class is now available for use within the body of this page. In fact, it is used in the body of the page to style the copyright notice.

Internal style sheets are handy if you want to create a style rule that is used multiple times within a single page. However, in some instances, you might need to apply a unique style to one particular element. This calls for an inline style rule, which enables you to specify a style for only a small part of a page, such as an individual element. For example, you can create and apply a style rule within a <p>, <div>, or <span> tag via the style attribute. This type of style is known as an inline style because it is specified right there in the middle of the HTML code.

Note

The <span> and </span> tags are dummy tags that do nothing in and of themselves except specify a range of content to apply any style attributes that you add. The only difference between <div> and <span> is that <div> is a block element and, therefore, forces a line break, whereas <span> doesn’t. Therefore, you should use <span> to modify the style of any portion of text that is to appear in the middle of a sentence or paragraph without any line break.

Here’s how a sample style attribute might look:

<p style="color:green;">
  This text is green, but <span style="color:red;">this text
  is red.</span>
  Back to green again, but...
</p>
<p>
  ...now the green is over, and we're back to the default color
  for this page.
</p>

This code makes use of the <span> tag to show how to apply the color style property in an inline style rule. In fact, both the <p> tag and the <span> tag in this example use the color property as an inline style. It is important to understand that the color:red; style property overrides the color:green; style property for the text between the <span> and </span> tags. Then in the second paragraph, neither of the color styles applies because this completely new paragraph adheres to the default color of the entire page.

Caution

Using inline styles isn’t considered a best practice when used beyond page-level debugging or the process of trying out new things in a controlled setting. The best practice of all is having your pages link to a centrally maintained style sheet so that changes are immediately reflected in all pages that use it.

Validating Your Style Sheets

Just as it is important to validate your HTML or XHTML markup, it is important to validate style sheets. You can find a specific validation tool for CSS at https://jigsaw.w3.org/css-validator/. You can point the tool to a web address, upload a file, or paste content into the form field provided. The ultimate goal is a result like the one in Figure 3.3: valid!

A screenshot shows the W 3 C C S S Validator.
Figure 3.3 The W3C CSS Validator shows there are no errors in the style sheet contents of Listing 3.1.

Summary

In this lesson, you learned that a style sheet can control the appearance of many HTML pages at once. It can also give you extremely precise control over the typography, spacing, and positioning of HTML elements. You also learned that, by adding a style attribute to almost any HTML tag, you can control the style of any part of an HTML page without referring to a separate style sheet document.

You learned about three main approaches to including style sheets in your website: a separate style sheet file with the extension .css that is linked to in the <head> of your documents, a collection of style rules placed in the <head> of the document within the <style> tag, and rules placed directly in an HTML tag via the style attribute (although the latter is not a best practice for long-term use).

Table 3.1 summarizes the tags discussed in this lesson. Refer to the CSS style sheet standards at www.w3c.org for details on what options can be included after the <style> tag or the style attribute.

Table 3.1 HTML Tags and Attributes Covered in Lesson 3

Tag

Attributes

Function

<style></style>

 

Allows an internal style sheet to be included within a document. Used between <head> and </head>.

 

type="contenttype"

The Internet content type. No longer required for HTML5.

<link>

 

Links to an external style sheet (or other document type). Used in the <head> section of the document.

 

href="url"

The address of the style sheet.

 

type="contenttype"

The Internet content type. No longer required for HTML5.

 

rel="stylesheet"

The link type.

<span></span>

 

Does nothing except provide a place to put style or other attributes. (Similar to <div></div>, but does not cause a line break.)

 

style="style"

Includes inline style specifications. (Can be used in <span>, <div>, <body>, and most other HTML tags.)

Q&A

Q. Say that I link a style sheet to my page that says all text should be blue, but there’s a <span style="font-color:red;"> tag in the page somewhere. Will that text display as blue or red?

A. Red. Local inline styles always take precedence over external style sheets. Any style specifications you put between <style> and </style> tags at the top of a page also take precedence over external style sheets (but not over inline styles later in the same page). This is the cascading effect of style sheets mentioned earlier in the lesson. You can think of cascading style effects as starting with an external style sheet, which is overridden by an internal style sheet, which is overridden by inline styles.

Q. Can I link more than one style sheet to a single page?

A. Sure. For example, you might have a sheet for formatting (text, fonts, colors, and so on) and another one for layout (margins, padding, alignment, and so on); you just need to include a <link> for each one. Technically, the CSS standard requires web browsers to give the user the option to choose between style sheets when multiple sheets are presented via multiple <link> tags. However, in practice, all major web browsers simply include every style sheet unless it has a rel="alternate" attribute. Best practices recommend that you limit the number of style sheets you link to. This results in fewer calls to the server and, therefore, faster page load times.

Workshop

The Workshop contains quiz questions and exercises to help you solidify your understanding of the material covered.

Quiz

1. What code would you use to create a style sheet to specify 30-point blue Arial headings and all other text in 10-point blue Times Roman (or the default browser font)?

2. If you saved the style sheet you made for Question 1 as corporate.css, how would you apply it to a web page named intro.html?

3. How many different ways are there to ensure that style rules can be applied to your content?

4. How do you connect all your website pages to the style sheet named mystyles.css?

5. In the following HTML, what color would the text “To come to the aid of their country” be?

<div style="color:purple;">
  Now is the time
  <p style="color:orange;">for all good people</p>
  <p>To come to the aid of their country.</p>
</div>

6. What does the display: block; property do?

7. What does the term px mean?

8. What does the style border-right: dashed red 2px; do?

9. What does the style border-radius: 1em 1.5em; do?

10. What does the style rule .main { color: purple; } do?

Note

Just a reminder for those of you reading these words in the print or e-book edition of this book: If you go to www.informit.com/register and register this book (using ISBN 9780672338083), you can receive free access to an online Web Edition that not only contains the complete text of this book but also features an interactive version of this quiz.

Answers

1. Your style sheet would include the following:

h1 { font: 30pt blue Arial; }
body { font: 10pt blue "Times New Roman"; }

2. Put the following tag between the <head> and </head> tags of the intro.html document:

<link rel="stylesheet" href="corporate.css">

3. Three: externally, internally, and inline.

4. To connect all your website pages to the style sheet named mystyles.css, use the following:

<link href="mystyles.css" rel="stylesheet">

5. It would be purple.

6. It displays the element on a new line.

7. It is a unit of measure—pixels.

8. It puts a right-side border on the element that is dashed, red, and 2 pixels wide.

9. It rounds the corners of the element with a 1-em horizontal radius and a 1.5-em vertical radius.

10. It sets everything with the class main to have a purple text color.

Exercises

  • Image Using the style sheet you created earlier in this lesson, add some style classes to your style sheet. To see the fruits of your labor, apply those classes to the HTML page you created as well. Use classes with your <h1> and <p> tags to get a feel for things.

  • Image Develop a standard style sheet for your website and link it to all your pages. (Use internal style sheets and/or inline styles for pages that need to deviate from it.) If you work for a corporation, chances are it has already developed font and style specifications for printed materials. Get a copy of those specifications and follow them for company web pages, too.

  • Image Be sure to explore the official style sheet specs at www.w3.org/Style/CSS/ and try some of the more esoteric style properties not covered in this lesson.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.233.58