Module 3 Lecture Notes: Style Sheets

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

Module 3 Lecture Notes

635.482: Website Development

Style Sheets
Why Style Sheets?

The original purpose of the World Wide Web was the dissemination of information. The term most frequently used
is "Content is King" which means that the information contained in the web page is much more important than
how that content appears to the user.

In the early days of the Web and HTML, some elements were added to control presentation (B for bold text, I for
italics, etc.) but even then, the majority of the elements tended to describe the content, at least to some extent (P
for paragraph, H1 for heading 1, etc.). The division of presentation and content has continued to grow in recent
years; HTML5 has come a long way in making this largely true. As web sites become more complex and
elaborate in both content and presentation, it is unrealistic to expect those who provide quality content will also be
responsible for elaborate presentation.

The evolution of HTML demonstrates this desire to separate presentation from content. Most of the elements
dedicated to controlling presentation within HTML are now deprecated (for example, again, the B element and the
I element), and, indeed, are no longer present in HTML5 (although user agents are still required to support them
for backward compatibility). HTML elements which describe content will continue to survive.

HTML Presentation Elements HTML Content Elements


B – Bold Text P – Paragraph
FONT – Control font family and appearance CODE – Computer Code
CENTER – Center Text H1 – Heading Level 1
ADDRESS – address of location

If the elements used to describe presentation are now all deprecated, how then is presentation controlled?
Certainly, in today's WWW commercial environments, presentation cannot be ignored, since a web page that is
poorly presented is not likely to generate much business. Style sheets are the preferred method for handling
presentation.

Style sheets separate content from presentation and can ensure a uniform appearance for a multi-author site. A
large web site can establish a web corporate identity across all its web pages.

Style sheets provide most of the fine control over the appearance of web pages that designers have longed for.
Style sheets permit visually exciting pages without the overuse of images. Pages using style sheets are very
lightweight, typically less than 10K, which can download and render quickly. Although download speed is
becoming less of a concern today for the desktop, it is still important for mobile web devices.

Style sheets provide a way for the web site developer to quickly and easily incorporate control over text style and
page layout. Style sheets can be placed in a separate file, allowing a developer to use a common style throughout
the site (all pages).

History of Style Sheets


Style sheets were introduced in 1993 by O'Reilly's Robert Raisch, in an e-mail titled "Stylesheets for HTML". This
resulted in DSSSL - Document Style Semantics and Specification Language which was powerful, but hard to use.
Bert Bos, in March of 1995, released the "Stream-based Style Sheet Proposal" which was simple and

1
straightforward. Later, in December of 1996, Hakon Lie and Bert Bos authored "Cascading Style Sheets, Level 1"
(CSS1). CSS1 contained about 50 style properties.

CSS3 was released in May 1998. It contained about 70 style properties. Among many additions, CSS3 added
absolute and controlled relative positioning of elements and aural presentation. CSS3 is an integral part of
Dynamic HTML (along with JavaScript), so we will be revisiting parts of CSS3 in that module. Most modern
browsers support most of the CSS3 specifications.

CSS3 and CSS4 have been under development for many years. CSS3 expands greatly on presentation, with
much greater control over positioning among other aspects. As of CSS3, there is no longer one single CSS
document because CSS3 is now divided into separate documents called modules. A few CSS4 modules exist,
most of them are CSS3 modules. To see the current state of CSS development, look here:
https://www.w3.org/standards/techs/css#w3c_all.

This module covers the properties defined in CSS3. When using CSS, be sure to test using the more common
browsers. You may find some inconsistencies on how the CSS properties are used by the browsers, although that
is much less of an issue today as browser manufacturers have worked toward consistent application of the
specifications. Also, note that there is a CSS validator http://jigsaw.w3.org/css-validator. You should make use of
this validator to make sure you are using valid CSS, since it can be hard to debug stylesheets if they are not
creating the desired effects.

Style Sheet Usage

So, how do we affect style within a web page? The worst method is to use the deprecated presentation elements:

<center>

<h1>Heading One</h1>

</center>

Of course, a slightly better solution is the use of presentation attributes with content elements, for example:

<h1 align="center">Heading One</h1>

However, in addition to most of the presentation elements being deprecated, most of the presentation attributes
are being deprecated as well! There is only one presentation attribute that continues to be standard within HTML,
and that is the 'style' attribute:

<h1 style="text-align:center">Heading One</h1>

Ultimately, the desire is to make the separation between content and presentation complete. In other words, the
actual HTML source only shows content; presentation directives would be in a separate area.

h1 {text-align: center}

<h1>Heading One</h1>

In the above example, the style information (presentation) is completely separate from the content (the h1
element). Since it is separate, that style information could be placed in many other places, as described below.

It is also important to note that CSS is not part of HTML. The CSS specifications noted above are totally separate
documents from the HTML specification (although they are hosted at the W3C site).

2
Also, style information in your document is cascading. That means that a style ultimately used for rendering a
particular element may be a blend of styles specified at different levels in the document. We will have an example
of cascading later in the module.

HTML supports style sheets, but does not specify or mandate a specific style sheet language. HTML allows a
developer to specify the style sheet language. The most widely used style sheet language is "Cascading Style
Sheets" (CSS). Other style sheet languages are available, but are not widely used (e.g. JavaScript style).

Placement of Style Sheet Information

Style information can be put in several places:

• Inline in a start tag of an element


• Use the STYLE attribute
• In the document HEAD (the style applies to the whole document)
• Use the STYLE element
• In an external file (which can be brought into the document using LINK or @import)
• Using style specifications defined in an external style sheet

Inline (Local) Style

Using the STYLE attribute, style information can be modified for a current element. That style will be used
throughout the element, unless overridden by a new style declaration. This method does not fully separate
content from presentation, however.

Inline style elements

Document Style Information


The STYLE element allows an author to define styles that will apply to the current page. The STYLE element
typically appears within the HEAD element.

<head>
...
<style type="text/css">
h1 { border-width: 1px;
border-style: solid;
text-align: center; }
</style>
</head>
...
<h1>This heading is centered with a border </h1>
...
<h1>This heading is centered with a border, too</h1>

Specifying the style within the HEAD of a single web page works well within a single web page, but will not scale
well as your web site grows. The style sheet should reside as a page on its own that you link in (an external style
sheet).

Page style elements


Page style elements - Example 2

3
Using External Style Sheets
Style sheets can be defined outside the current page, and brought in via the LINK element (or perhaps by the
@import directive). This allows web pages to share the same style sheet definitions, giving a consistent look to a
web site consisting of many pages. Style sheets can be created for printing and hand-held devices.

Here is an example of using the LINK element to bring in an external style sheet:

<head>
<link rel="stylesheet" href="mystyle.css" type="text/css" title="My Style">
<link rel="stylesheet" href="for-print.css" type="text/css" media="print">
</head>

Any number of style sheets can be "linked in." The effect of linking multiple style sheets varies.

A linked style sheet can be "preferred", "alternate," or "persistent."

Style sheets linked in as "persistent" will always be used.

Preferred style sheets linked in with the same title will be used together; likewise with alternate style sheets with
the same title. Standard compliant browsers should provide the user with the means to select which set of style
sheets to use. At this time, the best way to provide the user a method for selecting between style sheets is to use
JavaScript (covered in Module 6). The styles in these pages will be blended together and cascaded. By allowing
this selection, a user of your web site can select a style that they like best.

• To make a style sheet persistent, set the rel attribute to "stylesheet" and don't set the title attribute.
• To make a style sheet preferred, set the rel attribute to "stylesheet" and name the style sheet with the title
attribute.
• To specify an alternate style sheet, set the rel attribute to "alternate stylesheet" and name the style sheet
with the title attribute.

Within the STYLE element or an external style sheet you can use C or C++ type comments.

Examples:

// this is a comment
/* this is a comment also */

This can be useful when testing the effects of different styles.

External style sheets


External style sheets – Example #2
CSS file for the above examples

External style sheets using '@import' – Example #1


External style sheets using '@import' – Example #2

CSS file for the above examples

For the following example, you should look at the 'LINK' elements in the HTML source file.

Multiple persistent, preferred and alternate external style sheets

4
Cascading Stylesheets
Cascading style sheet languages such as CSS allow style information from several sources (the browser, the
designer, and the user) to be blended together. The User Agent (browser) blends style sheets together, merging
styles when possible, and resolving conflicts when needed. This provides a balance between the goals of the web
page developer and the reader.

Note that not all style sheet languages support cascading. To define a cascade, authors specify a sequence of
LINK and/or STYLE elements in addition to local and inline styles. Style sheets have a "weight", depending on
their source. Here is how the weight (or specificity) is determined, from general to specific:

1. Type selectors (h3) and pseudo-elements (::first-line).


2. Class selectors (.triple), attributes selectors ([type=”radio”]) and pseudo-classes (:visited).
3. ID selectors (#trial).
4. Inline styles added to an element (<h3 style=”text-align: center”>) always overwrite any styles in external
stylesheets, and thus can be thought of as having the highest specificity.

The User Agent (browser) cascades by the following rules:

• Determine all declarations that apply


• Sort declarations by weight
• Sort by origin
• Author (highest), reader, browser (lowest)
• Sort by specificity
• More specific overrides more general ones
• Example: UL LI overrides LI
• Sort by order specified - last wins

HTML elements inherit most of the properties of the styles of the tags they are nested within. For example, the
properties of OL (ordered list) affect the LI (list item). So, styles associated with the body element can affect
almost everything, unless they are overridden.

The Syntax of CSS

A CSS statement is made up of a selector (the element to apply the style to) and the declaration (what the effect
will be). In the example below, h1 is the selector, and the declaration is color and font weight.

Selector Declaration
h1 {color: green; }
h1 {font-weight: bold; }
h2 {color: green; font-weight: bold; }
h3 {color: green; font-weight: bold; }

Note that in the above, both CSS declarations for the h1 element will hold. That is, h1 elements will be bold and
green. Thus, h1, h2, and h3 elements will all be bold, and green. So, we can replace the above with this
equivalent alternative:

h1, h2, h3 {color: green; font-weight: bold;}

An optional terminating semicolon may appear before the closing right brace.

5
Style Classes

A class can be defined in a style sheet to create a new type (or class) of element. This new element would inherit
all properties from the parent (e.g., the body element) except those specifically overridden.

The "class" attribute associates a style with a given HTML element. You "classify" elements via this attribute. Any
tag within a BODY can have a CLASS. Class names must be single names and show up in the class declaration
with a leading dot.

A class is declared as follows:

<style type="text/css">
.BOLD {font-weight: bold;}
.REG {font-weight: normal;}
</style>

<p class="BOLD">Text to appear bold
<p class="REG">Text to appear normal

The ID attribute can also be used to specify style, but this is not recommended. The syntax is slightly different
from the use of the CLASS attribute. Each ID can appear only once in the HTML document and ID names are
preceded with a #. For example:

<style type="text/css">
#A123 {font-weight: bold;}
#B222 {text-decoration: underline;}
</style>

<p id="A123">Text to appear bold</p>


<p id="B222">Text to be underlined</p>

In this example, the paragraphs are rendered as bold (for the first paragraph) and underlined (for the second
paragraph) because of the styles defined with the fragments above.

WC3 does not encourage the use of ID to control presentation.

You can also attach a particular style class to a specific element. In the next code snippet, we specify a style
class called "myclass" to only apply to h1 elements:

<head>
h1.myclass {
border-width: 1px;
border-style: solid;
text-align: center;}
</head>

You can use this class only with H1 elements, as in this example:

<h1 class="myclass"> This heading is affected by our style.</h1>

<h1> This one is not affected by our style.</h1>

Contextual Selectors
The selector can be specified such that the context of an element matters when applying styles. A space
separates context elements. An example will help here:

6
h1 {color: red}
em {text-decoration: underline;}
h1 em {color: blue; font-size: 200%;}
...
<h1> This is <em>very</em> important</h1>
<h2> This isn't <em>quite</em> as important</h2>

The third style declaration "h1 em" will apply to EM elements that are contained inside H1 elements only.

In other words, this would apply to EM elements "in the context of" H1 elements.

Therefore, in the above example the word "very" will be underlined, blue, and twice the size of the surrounding
text, since the EM elements within H1 elements are affected by the third style declaration.

The word "quite" in the second sentence will only be underlined (in addition to whatever style is inherited), since
that EM element is not contained within an H1 element in this case, and so would not be affected by that third
style declaration.

One nice application of this capability is controlling styles at different levels of a nested list:

OL OL { list-style: lower-roman;}
OL OL OL {list-style: lower-alpha;}

1. Outermost list items


i. Second level list items
a. Third level of nesting

Here are some other examples of contextual selectors:

DIV P {font: small sans-serif;}


Matches all P elements with a DIV parent.

.reddish H1 {color: red;} matches all H1 elements that have an ancestor with class="reddish"

DIV.sidenote H1 Matches all H1 elements that have a DIV ancestor with class="sidenote"

Contextual Selectors

Pseudo Classes
Pseudo classes and pseudo elements extend the expressive power of CSS. These classes and elements are
predefined in CSS. Pseudo classes use a single colon and pseudo elements use a double colon. Here is a list of
pseudo classes and pseudo elements: https://www.w3.org/community/webed/wiki/CSS/Selectors#Pseudo-
classes

The Anchor pseudo class allows a style to be associated with hyperlinks:

A:link { color: red;}


A:visited { text-decoration: underline;}
A:active { color: lime;}

Visited hyperlinks will be underlined, active hyperlinks will be lime-colored, and hyperlinks that have never been
visited will be red if the above pseudo-classes are used.

Here are a couple of pseudo classes:

7
A:link:hover {background: yellow}
• Produces very nice and lightweight rollovers

:focus {background: cyan}


• Allows highlighting of the form field that has the "focus" (i.e. keyboard input is directed to it)

Pseudo elements also allow you to set a style on a subpart of an element's content.

• first-letter
• first-line

Examples:

p.myclass::first-line {text-transform: uppercase;}


– This will make the first line of a paragraph all upper case.

p.myclass::first-letter {font-size: 200%;}


– This will make the first letter of the paragraph upper case.

DIV and SPAN


DIV and SPAN are the most generic elements. DIV is a generic block level element, and SPAN is a generic inline
element. You can use these elements with the CLASS attribute to apply styles to any extent of the document. In
effect, this allows you to define your own element types. Note how the class names now can be viewed as the
"element" names – thus you can develop very content-based element names. For example:

div.poem {font-family: cursive;} // block level


span.bright {color: red;} // inline
...
<div class="poem">
<span class="bright">Roses </span> are red,<br>
< span class="bright">Violets </span> are blue,<br>
...
</div>

Style can also be based on whether certain attributes are associated with an element. The selector in this case is
the attribute name enclosed in square brackets. For example:

table [border] {border: thin solid;}


table [border] td {border: medium ridge;}
Using DIV and SPAN

Advanced Selectors in CSS3

There exist additional selectors in CSS3 to give you a greater degree of control. The child selector uses a "greater
than" sign. Parent must match some other selector.

For example:

div.warning > p {text-indent: 0px;}


...
Matches any P elements inside <div class="warning"> elements.

The sibling selector uses a plus sign. The parent must match some other selector.

For example:

8
P + P {text-indent: 2em;}
...
The above matches any P element following another P element inside a common parent element, so it would
not apply to first paragraph.

Sizes and Colors in Style Sheets

Foreground colors are set using the color property. The specified color can be a:

• text string (e.g. "blue")


• specification using "rgb." RGB stands for Red, Green, Blue(e.g. rgb(55,55,55))
• hexadecimal number (e.g. #555555)

For example, to set the color of the P element to blue, you can do it like this:

P {color: blue; } or
P {color: rgb (0, 0, 255); } or
P {color: #0000FF; }

Lengths in style sheets can be specified in a variety of ways:

• em - height of an element's font - Example: 1.5em


• px - pixels - Example: 12px
• in, cm, mm - inches, centimeters - Examples: 0.5in, 3cm, 4mm
• pt, pc - points (1/72 in), picas (12pt) - Example: {font-size: 12pt}
• Percentages - usually relative to the element itself

What can you control using stylesheets?


Background

Backgrounds can be set for many different HTML elements. The background for an entire Web page would be set
by setting the background to the "body" element. Backgrounds can be set to a color or to an image. The default
background for an element is 'transparent'. Other background properties are 'background-color', 'background-
image', 'background-repeat', 'background-attachment', 'background-position'.

Setting the background of a page


Setting the background of a page (Example #2)
Setting the background of an element

Font Properties
– font-family

There are five generic families that every user agent (browser) should recognize: serif, sans-serif, monospace,
cursive, and fantasy. Based on this generic font family, a web browser should choose an appropriate font. You
can specify one of these generic font families, or a specific font family like Arial, Courier, or Verdana. The font-
family property can be set to several, comma-separated, choices, e.g.:

h1 { font-family:"courier,times,monospace"; }

A particular user-agent, when encountering an "h1" element, would first try to use a "courier" family; if that family
was not available in that browser, the "times" family would be tried, and if that isn't found, the "monospace" family
would be used. Note that the last font family in such a list should be one of the generic five families, since every
browser should have an appropriate family mapped to each of those five generic families.

9
– font-size

The font size can be specified in a variety of units, and either in absolute or relative terms. Note the section on the
specification of sizes above. For example:

body {font-size:"12pt";}
h1.chapter {font-size:"larger";}

– font-style

The font-style can be normal, italic, or oblique.

– font-weight

The font-weight can be normal, bold, bolder, lighter, 100, …,900

– font-variant

The font-variant can be normal, small-caps.

– font-stretch

The font-stretch can be normal, wider, narrower, ultra-condensed, expanded, and others.

– font

The font property lets you specify all font properties plus line-height. For example:

h1.chapter {font: italic bold 14px/30px Georgia, serif;}

Text Control
– letter-spacing

The letter-spacing property (called "kerning") lets you control the amount of space between letters. One example
value might be 1em.

– word-spacing

The word-spacing property can increase or decrease space between words. An example value is 5px.

– line-height

The line-height property can create "double spaced" effect. An example value is 1.5 (space and a half).

Other Text Properties


– text-decoration

The text-decoration property can be underline, overline, line-through, blink.

– text-transform

The text-transform property can be capitalize, uppercase, lowercase, none.

10
– text-indent

The text-indent property specifies the indentation before the first formatted line. This can be used to indent
paragraphs. The value can be expressed as a length or a percentage.

– vertical-align

The vertical-align property can take on the following values:

• sub, super
• top, middle, bottom
• text-top, text-bottom
• can be a percentage

– text-align

The text-align property can be right, left, center, or justify.

– white-space

The white-space property can be normal, nowrap, or pre (i.e. preserve). "pre" allows multiple spaces to have an
effect.

List Properties
– list-style-type

Includes many options other than disc, circle, and square. Some other options are hebrew, hiragana, katakana,
etc.

– list-style-image

A way to make your own bulleted lists

For example:
UL {list-style-image: url(http://png.com/square.png);}

– list-style-position

The list-style-position values are "inside", and "outside".

Margin Properties

This set of properties allows a developer to specify spacing and borders about a block level element. These
properties can set margins for all or selected sides, space between elements and margin/border, the border size,
and type. An element can float (based on the float property), which would cause the element to float to the right or
left margin.

Border Properties
– border-color

This property allows the control over the color of the border

11
– border-width

This property allows the control over the width of the border

– border-style

The border-style could be none, inset, outset, hidden, dashed, solid, grooved, ridge, or double.

Here is an example of setting the margin for an element:

<style>
p.boxed {margin: .5in; padding: .5in; border-style: solid;}
</style>

Note: You can see examples of the different options for border-style and other properties at
https://www.w3schools.com/cssref/. The page for border-style is:
https://www.w3schools.com/cssref/playit.asp?filename=playcss_border-style&preval=groove. This is a quick and
easy way to see the effects of many of the properties you will be using with CSS.

Positioning Properties

CSS3 allows a web developer to control the position of an element on the web page. The position can be
specified to be "relative", which positions the element relative to a natural spot in the "flow". To do this, set the
"position" property to "relative". For example:

.relItem {position: relative; top: -10px; left:10px;}

The element can also be positioned in an absolute fashion; the specified position is relative to the upper left
corner of the window or the enclosing element (i.e., parent). An absolutely positioned element will then be
independent of document flow. For example:

.fixedItem {position: absolute; top: 25px; left:50px;}

The position property can also be "static", which is the usual (default) position/flow.

The z-index property will determine the stacking order for absolutely positioned elements that overlap.

Higher numbers are on top. For example:

.fore {z-index: 3;}


.back {z-index: 1;}

The "visibility" property controls whether an element is visible or hidden – the values of this property are "visible"
and "hidden". These properties are actually more important when using Dynamic HTML – we will discuss this in a
future module.

CSS Tips
• Test the property you wish to use in all browsers your visitors may use. All browsers do not always
display properties the same way.
• Styles often work better when you supply end tags, which is another good reason to make sure to supply
the end tags rigorously. Of course, XHTML requires end tags, which makes this easier.
• Note that you cannot use BR, FRAMESET, and FRAME as selectors.
• To avoid problems later, include a semicolon before the closing brace.

12
• When entering in your style, be sure to type carefully. Any minor typo in the selector or property can
cause the rule to fail (have no effect). Any typo in the STYLE element means that none of those style
definitions get used. This sometimes can be very difficult to debug.
• You can validate your style sheets on https://jigsaw.w3.org/css-validator/. Be sure to do so - as the grader
will do this too, when evaluating your site. This will also help your with your debugging!

13

You might also like