CSS SUMMARY
Where do you put the styles?
⚫ Style information can be located in three
places:
⚫ External to the pages in a site
⚫ Internal to each page
⚫ Inline with individual tags
⚫ Generally, creating an external style sheet file is the preferred
method. To take full advantage of CSS, the Style Sheet for a site
should be in this one external file, so that any changes will apply
throughout the site. This also means that only one style document
has to be downloaded for a single site.
2/5/2024 Using Cascading Style Sheets slide 2
Grouping Styles and Selectors
⚫ Each rule can include multiple styles by simply separating them by
semicolons:
h2 { color: darkblue; font-style: italic;}
⚫ Additionally, multiple selectors that have the same styles can be
grouped by separating them with commas:
h1, h2, h3 { color: darkblue; font-style: italic;}
⚫ Contextual selectors allow you to specify that something will
change, but only when it is used in conjunction with something else.
With the following style, strong will be displayed in red, but only
when it occurs within li within ul.
ul li strong { color: red;}
Elements being modified by contextual selectors need not appear
immediately inside one another (using this style, blah would still be
red text: <ul><ol><li><strong> blah </strong></li></ol></ul>).
2/5/2024 Using Cascading Style Sheets slide 3
Grouping Styles and Selectors
⚫ Direct child selectors allow you to specify that something will change, but
only those that are immediately inside of another element. With the
following style, only those strong elements that are directly inside of an h1
will be purple; no strong tags deeper within the sheet will be purple.
h1 > strong { color: purple;}
⚫ Adjacent selectors allow you to specify that something will change, but only
when preceded by something else. With the following style, only those links
(a) that are preceded by an h2 will be green.
h2 + a { color: green;}
Elements being modified by adjacent selectors appear immediately after
one another. Using this style, this link would be green: <h2>Visit
Stanford!</h2><a href="http://www.stanford.edu">click here</a>.
This link would not: <h2>Visit Stanford! <a href="http://www.stanford.edu">click
here</a></h2>.
⚫ You can also group selectors by attribute. With the following style, centered
h2 tags (<h2 align="center">) will be surrounded by a dotted border:
h2[align="center"] { border: dotted;}
2/5/2024 Using Cascading Style Sheets slide 4
How CSS Works — Rules
⚫ Rules provide presentation hints to browser
⚫ Browser can ignore hints
⚫ Three sources of rules:
⚫ User agent (browser's default settings),
⚫ Webpage (source file),
⚫ The user (personal settings in the browser)
⚫ Rules apply when selectors match context
⚫ E.g. p {text-indent:1.5em }
⚫ Selector is p (matches any <p> element)
5
Rules
⚫ Attached to elements
⚫ As attributes of elements (inline style)
⚫ Tied to id attribute of elements
⚫ Tied to class attribute of elements
⚫ Rules all have form
{Property Name : Value;}
⚫ Multiple rules separated by ;
6
Selectors
⚫ Can apply to every element of a type
E.g. h2
⚫ More often to a class of element
⚫ <cite class="textbook book">
⚫ Matches both textbook and book
⚫ Can apply to pseudo-elements
a:visited, etc.
7
Special Elements
div and span
⚫ Only for grouping other elements
⚫ div is block-level (think about paragraphs)
⚫ span is in-line (think about <code>)
8
Unit Measurements
⚫ In CSS, you can measure units either in absolute values or in relative values.
⚫ Absolute values are fixed, specific values. Since they are exact measurements, they allow the
designer complete control over the display of the web pages.
mm, cm, in, pt, pc, xx-small, x-small, small, medium, large, x-large, xx-large
⚫ Relative values have no fixed, specific values, and are calculated in comparison to something else
(usually the size of the default font or line size). Because different computers have different video
cards, screen sizes, and users have differing eyesight abilities, relative values tend to be a better
choice. They give the designer less absolute control but it often creates a better experience for the
visitor.
em, ex, px, larger, smaller, num%
⚫ Examples:
body { font-size: 12px; }
h1, h2, h3 { line-height: 200%;}
⚫ Note – a warning about using percentages: if you use percentages, and nest an element inside of
that same element, the percentages will be cumulative.
2/5/2024 slide 9
Using Cascading Style Sheets
Font and Text Styling
When choosing a font, there are several things to keep in mind:
1. Not everyone has the same set of fonts.
2. If you use a font that the visitor doesn’t have, the page will display in the default
font (usually Times), unless you provide more choices. To do this, add more
than one font in your declaration, and always end with the font family (serif,
sans-serif, or monospace):
font-family: Verdana, Arial, Helvetica, sans-serif
3. Documents designed to be printed tend to look better in Serif fonts (Times,
Georgia, Book Antiqua, etc.)
4. Documents designed to be viewed onscreen tend to look better in Sans-serif
fonts (Verdana, Arial, Helvetica, etc.)
To apply a font to the entire web page, modify the body tag:
body {font-family: Verdana;}
To apply a font to a specific section of text, create a class, and use the
span tag with that class:
.neatstuff {font-family: Comic Sans MS;}
<span class="neatstuff">This is in Comic Sans</span>
2/5/2024 Using Cascading Style Sheets slide 10
Modifying List Elements
⚫ By default, unordered lists (<ul>) appear as bullets and ordered lists (<ol>)
appear as numbers in HTML.
⚫ Using CSS, you can modify how list items will appear:
⚫ Properties:
list-style, list-style-type, list-style-image, list-style-position
⚫ Values:
disc, circle, square, decimal, decimal-leading-zero, lower-roman, upper-roman, lower-alpha,
upper-alpha, lower-greek, lower-latin, upper-latin, hebrew, armenian, georgian, cjk-
ideographic, hiragana, katakana, hiragana-iroha, katakana-iroha, none, url("graphic.gif")
⚫ Examples:
ul { list-style: disc; }
ol { list-style: upper-roman;}
li { list-style: url("blackball.gif");}
ul li { list-style-position: inside;}
2/5/2024 Using Cascading Style Sheets slide 11
How CSS Works — Matching
⚫ Every HTML document represents a document tree
⚫ The browser uses the tree to determine which rules
apply
⚫ What about inheritance? And conflicts?
12
HTML Parse Tree
<html>
<head>
<meta … />
<title>…</title>
</head>
<body>
<h1>…</h1>
<p>…</p>
<ul>
<li>…</li>
<li>…</li>
<li>…</li>
</ul>
<p>…</p>
</body>
</html> 13
Inheritance in CSS
The Cascade
⚫ Inheritance moves down tree
⚫ Cascading move horizontally
⚫ It works on elements that the same rules apply to
⚫ It is only used for tie-breaking when ≥2 rules apply
⚫ The highest ranking rule wins
⚫ Most specific wins (usually)
⚫ But important rules override others
⚫ !important beats plain
⚫ User's !important beats everything else
14
Hierarchy of styles
⚫ When style information is located in all three places in one site, the
hierarchy is as follows:
⚫ External Style Sheets affect the entire site.
⚫ Internal styles affect only their own pages and override external styles.
⚫ Inline styles affect only their own tags and override both internal and external
styles.
⚫ For example, if an external Style Sheet sets <h2> tags to purple and
a particular page has an internal style that changes that color to
orange, the <h2> tags will be orange only on that page and
nowhere else in the site. If there is a single <h2> tag on that page
which specifies green as its color, then the color for that one tag will
be green. All other <h2> tags on that page would be orange; the
<h2> tags on the rest of the site would be purple.
2/5/2024 Using Cascading Style Sheets slide 15
!important
⚫ Normally, the last rule listed in the cascade will take precedence
over previous rules. In this example, the body font will be Verdana,
not Times.
body {font-family: Times;
font-family: Verdana;}
⚫ However, by entering !important in a rule, that rule will take
precedence, regardless of its location. In this example, the body
font will be Times, not Verdana.
body {font-family: Times !important;
font-family: Verdana;}
Note: !important does not work with all properties in Internet Explorer.
2/5/2024 Using Cascading Style Sheets slide 16
Pseudo-Elements?
Pseudo-Attributes?!
‘CSS introduces the concepts of pseudo-elements and pseudo-classes to
permit formatting based on information that lies outside the document tree.’
⚫ Classes ⚫ Elements
⚫ :first-child ⚫ :first-line
⚫ :link, ⚫ :first-letter
:visited ⚫ :before,
⚫ :hover,
:after
:active,
:focus CSS 2.1 §5.10
⚫ :lang Pseudo-elements
and pseudo-classes
How To Include Rules
⚫ Inline
<p style=“text-align: center” >…</p>
⚫
⚫ Inside the head element
⚫ <link rel="stylesheet"
type="text/css" href="site.css" />
⚫ <style type="text/css">…</style>
⚫ <style type="text/css">
@import url(site.css);
/* other rules could go here */
</style>
18
Simple Example
<p>This is some text inside a
body { background-color:
<code>p</code> element.</p>
rgb(80%,80%,80%); color: black }
<p>This is <em>some
emphasized text</em>. This is
regular text.</p> em { text-decoration: underline;
<p class="large" color: red; background-color:
inherit; font-weight: bold }
>This is some text in class
<code>large</code>
element.</p> .large { font-size: 2.5em; }
<p class="large“>This is <span
class="large”>some
<em>emphasized text</em>
in</span> class
<code>large</code>.</p>
19
A Very Brief Overview of
Visual Formatting With CSS
⚫ Visual Formatting
⚫ Fonts
⚫ Colours
⚫ Position
⚫ Box model and Borders
20
Visual Formatting: fonts
⚫ Some major properties
⚫ font-family
⚫ body {font-family: Garamond, Times,
serif}
⚫ Serif fonts and sans-serif fonts
⚫ font-size:
Length (em,ex), percentage, relative size, absolute size
⚫ font-style:
Normal, italic, oblique
⚫ font-weight:
Lighter, normal, bold, bolder, 100, 200, …, 800, 900
Set all at once with font
21
⚫
Visual Formatting: Colours
⚫ How to specify
⚫ 16 Predefined names
⚫ RGB values (%, #, 0…255)
⚫ System names: e.g. CaptionText
22
Visual Formatting: Colours (cont.)
⚫ Major properties
⚫ background-color
⚫ color
⚫ transparent and inherit values
23
Classes and IDs
⚫ HTML has two attributes that make CSS even more useful: class and ID. They make
it easy to apply style to just about any tag.
⚫ Classes can describe a generic style that can be applied to any HTML element, or
can be created for specific elements.
⚫ When defining a style for elements with a particular class attribute in the Style Sheet,
declare a rule using a dot (.) followed by the class name. To limit the style to a
particular element with that class attribute, use a selector combining the tag name
with a dot followed immediately by the class name.
⚫ The following rule would apply to any element with the attribute class=“shade"
.shade { background: yellow; }
⚫ The following rule would apply only to paragraph tags with the class shade (<p class="shade">)
p.shade { background: red; }
⚫ IDs are similar to classes, but IDs are unique – they can only be used with one
instance of an element within a document.
⚫ When defining a CSS rule using an ID-based selector, use a number/pound/hash
sign (#) followed by the style name. To limit the style to a particular element with that
id attribute, use a selector combining the tag name with a # and then the id name.
⚫ The following rule would apply to any element with the attribute id="intro"
#intro { font-size: 2em; }
⚫ The following rule would apply only to heading 1 tags with the id intro (<h1 id="intro">)
h1#intro { color: green; }
2/5/2024 Using Cascading Style Sheets slide 24
Class example
⚫ Here’s an example of a web page with an
internal CSS style with a class called
“highlight”:
2/5/2024 Using Cascading Style Sheets slide 25
Inline vs. Block Display (HTML)
⚫ All HTML elements (tags) are assigned a display
property value of either inline or block.
⚫ Inline elements display in browsers horizontally.
[INLINE ELEMENT 1] [INLINE ELEMENT 2] [INLINE ELEMENT 3]
⚫ Block elements display in browsers vertically
(stacked one on top of the other).
[BLOCK ELEMENT 1]
[BLOCK ELEMENT 2]
[BLOCK ELEMENT 3]
⚫ Examples of inline elements:
<a> <img> <strong> <em> <span>
⚫ Examples of block elements:
<p> <h1-h6> <div> <hr> <table> <ul>
2/5/2024 <ol> Using Cascading Style Sheets slide 26
Inline vs. Block Display (CSS)
⚫ Using CSS, you can change this inherent
display property:
⚫ To force a block display, use the declaration
display: block;
⚫ To force an inline display, use the declaration
display: inline;
⚫ To force a list, use the declaration display:
list-item;
⚫ To hide elements matching the selector, use the
declaration display: none;
2/5/2024 Using Cascading Style Sheets slide 27
Example – display: block;
⚫ Normally, <a> tags display inline.
⚫ But, if you add the style a {display: block;}, they
will display as a vertical navigation menu:
2/5/2024 Using Cascading Style Sheets slide 28
Example – display: inline;
⚫ Normally, the heading tags display in block
format:
⚫ But, to have them display inline, add the style
h1,h2,h3 {display: inline;}:
2/5/2024 Using Cascading Style Sheets slide 29
Span and Div
⚫ There are two tags that are particularly useful when
using CSS: <span> and <div>. They are both
container tags that have minimal formatting associated
with them.
⚫ The <span> tag is an inline element that simply holds
text without doing anything special to it.
⚫ The <div> tag is a block element and causes the text it
encloses to start on a new line.
⚫ Using <span> and <div> tags in conjunction with
classes and IDs allows for great flexibility in creating
pages.
2/5/2024 Using Cascading Style Sheets slide 30
Example using SPAN, DIV, Class, and ID
⚫ Here’s an example of a web page using a class, an id,
and the span and div tags:
2/5/2024 Using Cascading Style Sheets slide 31
Visual Formatting: Images
⚫ position:
static, relative, absolute, fixed
⚫ Static — normal elements
⚫ Relative — translate from usual position
⚫ Absolute — scroll with the page
⚫ Fixed — like absolute, but don't scroll away
⚫ Example:
32
Visual Formatting: Images (cont.)
⚫ z-index: depth
⚫ float and clear
⚫ float: left or float: right or float: none
Position relative to parent element
⚫ Reset with clear
<br style="clear:both" />
33
Visual Formatting: Box Model
Margin
Border
Padding
34
Box Model (Cont.)
⚫ Padding
⚫ Size in %, em, or ex for text
⚫ padding-top, padding-right, padding-bottom, padding-left
Mnemonic: TRouBLe
⚫ Set all at once with padding
⚫ Margin Width is of content only.
⚫ Similar to padding Neither the border nor the
⚫ But can also be auto padding are included in width.
⚫ Example
<style type="text/css" media="screen">
body {text-align: center;}
div#card {width: 575px; margin-left: auto; margin-right: auto;} 35
</style>
Making Room for a
fixed position object
body
{margin-left: 6.3em}
div.up
{position: fixed;
left: 1em;
top: 40%;
padding: .2ex;
min-width: 5.5ex }
mp Box’
36
Formatting The ‘Jump Box’
‘Jump Box’
37
Basic Formatting of the
‘Jump Box’
HTML Outline
Extract of CSS Rules
<body> body
<!-- … --> {margin-left: 6.3em}
<div class="up"> div.up
<dl> {position: fixed;
<dt>Jump to left: 1em;
top</dt> top: 40%;
<!-- … -->
padding: .2ex;
</div>
min-width: 5.5ex }
</body>
Make these changes one after the other
• body {padding:4em} 38
• div.up {margin: 4em}
• div.up dl {margin:4em}
Button Example
Class Exercise: HTML File
<p class="nav-bar" >
<span class="noCSS">Homepage sections:<br /></span>
<span class="button"><a href="1.html" > address</a></span>
<span class="noCSS"> |</span>
<span class="button"><a href="2.html">research</a></span>
<span class="noCSS"> |</span>
<span class="button"><a href="3.html"> teaching</a></span>
<span class="noCSS"> |</span>
<span class="button"><a href="4.html"> <abbr
title="graduate">grad</abbr> students</a></span>
<span class="noCSS"> |</span>
<span class="button"><a href="5.html“> other</a></span>
</p> 39
Class Exercise : CSS file (Cont.)
.noCSS {visibility:hidden} /* any element */
p.nav-bar {text-align: center} /* only those P elements */
span.button {border-style: outset; /* button shape */
width: 17ex; padding: .2ex; border-color: #ffc; /* colours */
background-color: #ccc; color: #c00;
font-weight: bold; /* text effects */
text-align: center;
text-transform:capitalize}
/* links inside buttons */
span.button a {text-decoration:none}
span.button a:active, /* note comma and ... */
span.button a:visited, /* ... pseudo-classes */
span.button a:link {color:#c00; background: inherit} 40
span.button a:hover {color:#33f; background: inherit}
Pseudo-elements and Pseudo-
classes
⚫ Two special predefined groupings, called pseudo-elements and pseudo-
classes, are used in CSS to deal with special situations that do not exist
with standard HTML. For example, under standard HTML, there is no way
to automatically change the look and feel of the first letter or line of a
paragraph. But by using the pseudo-element :first-letter you can
specify a style that affects it:
p:first-letter { font-size: 200%; color:red;}
⚫ Under standard HTML, there is no mechanism to deal with mouse
movements. But with CSS, the pseudo-class :hover can be used to
change the style of a link. In this example, a:hover is used to change the
link color to red and the underlining to disappear whenever a mouse hovers
over links:
a:hover {color: #ff0000; text-decoration: none;)
⚫ To change the style of links, use the pseudo-class :link
To change the style of visited links, use the pseudo-class :visited
a:link {color: #00f; font-weight: bold;)
a:visited {color: purple; border: groove;}
2/5/2024 Using Cascading Style Sheets slide 41
Positioning
⚫ Using CSS, you can place elements exactly on a page
using a technique called “positioning.” Positioning is
determined by an X axis and Y axis. To specify a
specific point on the screen, you can use the X and Y
coordinate for that point.
⚫ There are several ways to specify position in CSS:
absolute, relative, fixed, inherit, and static.
⚫ The three most often used are absolute, relative, and
fixed.
⚫ Internet Explorer 6 only recognizes absolute and relative.
2/5/2024 Using Cascading Style Sheets slide 42
Absolute, Relative, Fixed, Inherit, and Static
Positioning
⚫ Absolute positioning defines the position of a given bounding box from the
top and left side margins of the web page. This not only allows objects to
be placed in an exact location, it also allows objects to be placed one on top
of another.
⚫ Relative positioning defines the positioning in such a way that elements are
offset from the previous element in the HTML code. This allows objects to
be placed in relation to one another.
⚫ Fixed positioning defines the position of a given box relative to the window
and remains in its specified location even as the content scrolls underneath
it. This value does not work in Internet Explorer 6 or earlier. In IE 7, the
browser must be in “standards-compliance mode”.
⚫ Inherit positioning explicitly sets the value to that of the parent (if the parent
is position:absolute, the child will be position:absolute; if the parent is
position:fixed, the child will be position:fixed).
⚫ Static positioning is the default. It defines the position of a given box
essentially as an unpositioned element – it flows in the normal rendering
sequence of the web page.
2/5/2024 Using Cascading Style Sheets slide 43
Absolute Positioning Example
2/5/2024 Using Cascading Style Sheets slide 44
Relative Positioning Example
2/5/2024 Using Cascading Style Sheets slide 45
Fixed Positioning – code view
<div id="main">
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Quisque ultrices, nibh ac rhoncus fermentum, orci sem
dapibus nisi, sed tincidunt lectus lectus at augue. In
consectetuer vehicula enim. In hac habitasse platea
dictumst. Donec a nisl vitae tortor tristique viverra.
Sed at lorem a ante lobortis molestie. Nulla ullamcorper
urna accumsan diam. Aliquam non eros. Pellentesque egestas
ultricies enim. Aenean lobortis. Nulla interdum commodo
turpis. Sed ut mi id elit vehicula sollicitudin. Sed
lobortis, ligula sit amet euismod egestas, mi ante
iaculis nunc, ut rhoncus magna lectus ac arcu. In hac
habitasse platea dictumst. Proin quis ligula vitae quam
pharetra adipiscing. Pellentesque tincidunt suscipit
nibh. Ut fermentum suscipit justo. </p>
<p>Fusce purus lectus, ultricies nec, aliquam at, facilisis
id, arcu. Vestibulum quis mi vel massa porta hendrerit.
Nulla ullamcorper ligula nec lectus. Quisque tempor,
augue in molestie gravida, eros arcu luctus tortor, eu
dignissim diam urna sed urna. Ut dictum ultrices lacus.
In hac habitasse platea dictumst. Suspendisse sed purus
blandit metus ultricies suscipit. Proin diam justo,
consequat id, rhoncus eget, facilisis ut, lacus. Vivamus
dignissim dui in justo. Suspendisse elit. Nam nulla
tortor, fringilla sed, faucibus quis, ullamcorper a,
leo. Fusce blandit condimentum turpis. Pellentesque vel
odio et odio suscipit egestas. Nullam ullamcorper
sagittis ipsum. Maecenas fringilla malesuada pede. Duis
ut quam. </p>
</div>
<div id="links">
<p>This area is fixed and will never move. It's good for
things like navigation bars.</p>
<ul>
<li><a href="page1.html">Page 1</a></li>
<li><a href="page2.html">Page 2</a></li>
<li><a href="page3.html">Page 3</a></li>
<li><a href="page4.html">Page 4</a></li>
<li><a href="page5.html">Page 5</a></li>
</ul>
</div></body></html>
2/5/2024 Using Cascading Style Sheets slide 46
Fixed Positioning – Firefox
web browser
2/5/2024 Using Cascading Style Sheets slide 47
Layers and the “Bounding Box”
⚫ When the browser draws an object on a page, it places it into an
invisible rectangular space called a “bounding box.” You can set the
box’s exact location on the page or offset it from other objects on the
page. As mentioned in the previous slides, you can also specify the
size of the box.
⚫ With CSS, these boxes can be stacked one on top of another as
layers. Horizontal and vertical positioning happen along the X and Y
axes, and the layered positioning happens along the Z axis.
⚫ The Z axis is set using the CSS style z-index, which allows you to
specify which layer appears on top of the others. By setting the z-
index higher or lower, an object can move up and down a stack.
The higher the z-index, the more “on top” it is.
2/5/2024 Using Cascading Style Sheets slide 48
Layering Example 1
2/5/2024 Using Cascading Style Sheets slide 49
Layering Example 2
2/5/2024 Using Cascading Style Sheets slide 50