CSE 134B Web Client Languages
Quick Overview of
CSS 1-3
Adopted and Extended from Chapters 10 and 11
of HTML & XHTML: The Complete Reference, 4th Edition and 4 and 6
from the 5th edition
CSE 134B Web Client Languages
CSS Standards and Support
• CSS1 (http://www.w3.org/TR/REC-CSS1) – Dec 1996, revised 1999
• CSS2 (http://www.w3.org/TR/REC-CSS2/ ) - May 1998
– Major contribution so far is support of positioned regions
– Replaced the interim CSS-P (Positioning) standard
– Provides a number of other features including alternate styles,
aural styles, new selectors, improved lists, etc.
• CSS 3 (http://www.w3.org/Style/CSS/current-work) – in progress
• Significant spec re-org (modularization)
• Lots more selectors, fonts, improved color handling, internalization
features
• Cross-browser support was initially spotty for CSS, but
later all the browsers get the basic stuff correct
• Today the nightmare continues because vendors keep
introducing new properties and the CSS3 specification is
a moving target
• The next slide should serve as a visual reminder of how
visual distortions manifest themselves with CSS at times
CSE 134B Web Client Languages
The Bad Old Days!
Past
Present and Future – caniuse.com Is today really better or worse?
CSE 134B Web Client Languages
CSS Basics
•
Concept of style sheets is to separate the structure of the document (in
(X)HTML) from the style/presentation of document (in CSS)
Note: Never a full decouple, CSS of course relies on markup for correct
binding. Goal is more a loose couple
•
•
Pros
– Allows different styles depending on the situation
– Make maintenance easier
– Separation of work concerns
– Theoretically makes files smaller
Cons
– Browser support, compatibility, bugs and quirks
• The devil you know vs. the one you don’t
– User misunderstanding
• Bad markup, lack of true tree understanding, measurement fun, and of course dreaded workaround
CSE 134B Web Client Languages
CSS Basics
• The style sheet itself is just a collection of rules of the format:
selector {rule; … rule n;}
– Selector may be a particular tag specified by id, a group of tags
by class or location in parse tree, tags of a particular type, tags
in a particular state (ex. Hover) and on an on
– Rules always separated by semi-colons except final rule where
semi-colon is optional
CSE 134B Web Client Languages
You can certainly make mistakes
Though you can validate your CSS…but be careful
CSE 134B Web Client Languages
Valid CSS doesn’t imply valid HTML
Though on a pure acceptance of it “looking right” you might go
with these problems. It will catch up with you when you get to
JavaScript though!
CSE 134B Web Client Languages
Adding Style
Three primary ways to add style to a document:
1.
External style sheets
• Pros: Can set styles for many pages in a site with one document
• Cons: Extra download for style sheet.
2.
Document wide style sheets
• Pros: Control document style in one place. No additional
download.
• Cons: Need to reapply style for subsequent pages.
3.
Inline style
• Pros: Can control style to a single character, overrides other
styles
• Cons: Need to reapply for every document. Bound to closely to
tags so as to be little more than a new tag.
CSE 134B Web Client Languages
Linked Style Sheets
• Start with linked style (external style) we need to put all the style
rules in a .css file (e.g. corpstyle.css)
• The .css file would simply contain rules and nothing else like so
/* I am just a CSS comment in a linked file */
body {font: 10pt; font-family: Impact;
color: yellow; background-color: #000000;}
h1
{font: 28pt; font-family: Sans-Serif;
color: green;}
a:link {color: #ff0000; text-decoration: none;}
.important {background-color: yellow;
font-weight: bold;}
#note {background-color: orange;}
CSE 134B Web Client Languages
Linked Style Sheets Contd.
•
In the HTML file we would bind the external style sheet with a <link> tag
<link rel=″stylesheet″
href=″styles/corpstyle.css″
type=″text/css″ />
•
You should also specify a media attribute to indicate what media the style should
apply to.
<link rel=″stylesheet″
href=″styles/corpstyle.css″
type=″text/css″ media=″screen″ />
– Widely supported media types: print, screen, all
– Other media types: aural, braille, embossed, handheld,
projection, tty, and tv
CSE 134B Web Client Languages
Media Types
• You do not necessarily need to use linked styles to use media values
consider using @media rules like so
<style type="text/css">
@media screen {body
{font-family: sans-serif;
font-size: 18 pt;}
}
@media print {body
{font-family: serif;
font-size: 9 pt;}
}
</style>
Note: Be careful of the double { }’s here!
** Interesting newer idea – media queries
Demo: http://htmlref.com/ch6/mediaquery.html
CSE 134B Web Client Languages
Printer Style Sheets
• The most common use of linked styles is to define a separate look
for print (usually turning off various navigation items and changing
content width for more efficient paper use)
<link rel="stylesheet" href="screenstyle.css"
media="screen" type="text/css" />
<link rel="stylesheet" href="printstyle.css"
media="print" type="text/css" />
CSE 134B Web Client Languages
Printer Style Notes
• There are some special printer specific properties of
varying browser support like page-break-before and
page-break-after that are useful for print output
• You may find it better to measure using in,cm,pt,pc,
etc. for printout
• Be careful about the difference between 8.5 x 11 and A4
• Microsoft has some proprietary printer CSS if you really
want control and want to stay away from PDF
• Consider that a special “print version” button does have
some value since what you see on screen is not what you
get with printer styles!
– Users may not like that surprise?
CSE 134B Web Client Languages
Alternative Styles
• You can provide multiple styles and the browser or
JavaScript can be used to toggle between them.
<link rel="stylesheet" href="standard.css"
id="standardstyle" title="standard" type="text/css" />
<link rel="alternate stylesheet" href="orange.css"
id="altstyle1" title="halloween" type="text/css" />
<link rel="alternate stylesheet" href="greenandred.css"
id="altstyle2" title="xmas" type="text/css" />
CSE 134B Web Client Languages
Alternative Styles Example
CSE 134B Web Client Languages
Alternate Styles Notes
• Because users will unlikely know how to set alternate
styles in their browsers you should use a site/page tool
for visual customization
– Note: Supporting alternate styles this way with JavaScript can
address how to support alternate styles in other browsers
CSE 134B Web Client Languages
User Styles
• Users can define their own linked styles which will
override author styles
This image cannot currently be displayed.
CSE 134B Web Client Languages
Type Attribute
• To be precise you should set the type attribute of <link> and <style>
tags to indicate the type of style sheets in use (ex. text/css)
• You may also set these values in one place using a <meta> tag
<meta http-equiv="Content-Style-Type"
content="text/css">
• Alternatively this value can be emitted in the HTTP response headers
Note: If you use the <meta> or HTTP method you are actually
redundant in specifying the type on the tags later interestingly there
may be support issues here with validator and browsers
Tip: Given that modern Web only supports CSS many developers opt for not
bothering with types just as we assume JS is in use for <script> tags.
CSE 134B Web Client Languages
Document-Wide Style
• Use the <style> tag to create a document wide style
sheet in the <head> of the document.
<!doctype html>
<html>
<head>
<title>CSS Test</title>
<style type=″text/css″ media= ″all″>
body {background: white; margin-left: 1in; margin-right:
1.5in;}
h1 {font-size: 24pt; color: #FF0000; text-align: center;}
p {font-size: 12pt; text-indent: 0.5in; color: #000000;}
</style>
• It is possible to have numerous <style> tags but in the
past was thought as poor usage unless media types are
employed
• Today with rise of scoped styles we likely will see
documents with many <style> tags in them
CSE 134B Web Client Languages
Comment Masks
• Given that user-agents will treat the contents of unsupported tags
as content it is useful to “mask out” the content of a document
wide style using standard HTML comments in case we have some
oddball user-agent reading the page
<style type="text/css">
<!-body {background-color: #FF0000;}
-->
</style>
• Given the rise of standards oriented design this may be incorrect
and you may have to use a CDATA section instead
<style type="text/css">
<![CDATA[
/* CSS goes here */
]]>
</style>
CSE 134B Web Client Languages
Comment Masks Contd.
• Unfortunately the previous solution while valid doesn’t really do
what is intended since a non-conforming or older user-agent may
have a hard time with a CDATA section
• You might try combine efforts and use a solution along the lines of
this, but be pragmatic please!
<style type="text/css">
<!--/*--><![CDATA[/*><!--*/
CSS goes in here
/*]]>*/-->
</style>
CSE 134B Web Client Languages
Importing Styles
Import fragments of CSS using @import. For example
<style type=″text/css″>
@import ″corpstyle.css″
@import ″docstyle.css″
h1 {color: #FF0000;}
</style>
•@import is used less as a macro and more to hide CSS from some ancient
browsers
@import “hide.css”; /* should hide from IE4 and N4 */
@import url(hide.css) screen; /* hides from Nav 4, IE 5-6 */
•Unfortunately this is a great example of a CSS hack and and like other hacks
you may see side-effects such as the Flash of Unstyled Content (FOUC)
CSE 134B Web Client Languages
Inline Style
• The core attribute, style, which is defined for nearly
any element and allows us to define styles right inline
<h1 style=″font-size:48pt;color:#00CC00;″>CSS1
Test</h1>
• Since browsers ignore attributes they don’t understand
this degrades to whatever the default tag rendering is
in a non-CSS conforming user agent
• Inline style bound is very closely to a particular tag,
somewhat reducing the theoretical value of CSS
• As the most specific type of rule, these properties will
always beat out others power-wise
CSE 134B Web Client Languages
Tips on CSS Rule Inclusion
• Adding in multiple <link> tags for the same media type
is a bad idea unless you are doing some form of browser
selection
– Network roundtrips and cache check issues
• Multiple <style> tags is pretty much pointless again
unless you are using media types or some other selection
technique
• CSS files can be condensed (whitespace, comment
remove, rule reduction) since they are becoming quite
bloated especially when using numerous class names
– Consider automatic id and class name management
CSE 134B Web Client Languages
Using CSS Properly with (X)HTML Tags
•
A common problem we see is using the generic <div> (block) and <span>
(inline) tags to recreate functionality. This is common in sites that use <div> tags
almost exclusively and then add large numbers of class values to define meanings
–
Example
<div class=″largeHeading″>…</div>
<h1 class=″largeHeading″> … </h1>
–
–
BAD
BETTER
HTML5 improves our selection of semantic tags to choose from.
Trouble can ensue when you start changing the default tag renderings particularly
with more physical style markup
– <b style=″font-weight: normal;
font-style: italic; ″>Bold?</b>
CSE 134B Web Client Languages
Tag Selectors
• The most basic selector is the tag selector
strong { color: #ff0000; }
/* make all strong tags red */
• Q: Are simple selectors case sensitive? Would it depend
on language type?
• What about other tags that are made up?
halloween {background-color: #FF9900;
color: #000000;}
CSE 134B Web Client Languages
id Selectors (#)
• All elements can be named with the core attribute id for
access via CSS
<h1 id=″FirstHeading″>I am a heading!</h1>
• Use a selector like
#FirstHeading {font-size: 28pt; color: red;}
to style the named tag.
• Commonly it is seen that CSS developer use more precise
rules
h1#FirstHeading {font-size: 28pt; color: red;}
• Is it questionable the value of such rules since you are
not supposed to have similar id values in (X)HTML?
CSE 134B Web Client Languages
class Selectors (.)
• The class attribute is used to create a grouping or to
associate like elements
<p class=″myclass″>, <h1 class=″myclass″>
• Then use the class selector (.) to style these tags
.myclass {background-color: yellow;}
• A common aspect of classes overlooked is that a tag may
belong to many classes (separate name in spaces)
<p class=″myclass otherclass somethingelse″>
• Doing more specific rules based upon classes can be
quite useful
h1.myclass {font-size: xx-large;}
/* just apply to h1 of this class */
a.nav {text-decoration: none;}
/* change link style only in some cases */
CSE 134B Web Client Languages
Considerations with class and id
• Often designers make everything a class since
they believe they may reuse it
– Reason you might want to use an id
• Easier scripting
• Link targets
• Caught in validation if truly supposed to be unique
• Name collision will happen as you start building
large sites and style sheets
– Shouldn’t you have unique identifiers by document?
• File: home.html - #homeNavbar
• File: sub.html - #subNavbar
CSE 134B Web Client Languages
Selector Grouping
• Grouping is possible to apply the same rule to
many items
h1, h2, h3 {background: #FF0000;}
• Reasons why same look and different tag
– Semantic meaning of tags
– Using the cascade to shorten rules or improve
flexibility of the style sheet
CSE 134B Web Client Languages
Document Trees
• The key to understanding the CSS is how markup
is modeled as a tree. Consider
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>DOM Test</title></head>
<body>
<h1>DOM Test Heading</h1>
<hr>
<!-- Just a comment -->
<p>A paragraph of <em>text</em> is just an example</p>
<ul>
<li><a href="http://www.yahoo.com">Yahoo!</a></li>
</ul>
</body>
</html>
CSE 134B Web Client Languages
Modeled Document Tree
CSE 134B Web Client Languages
Inspected Parse Tree
CSE 134B Web Client Languages
Malformed Parse Trees
• What happens if you screw up your markup?
CSE 134B Web Client Languages
Malformed Parse Inspected
CSE 134B Web Client Languages
Malformed Parse Take 2
CSE 134B Web Client Languages
Render Engine Issues Reminder
•
Always consider what
rendering mode the
browser is in
Two general modes
•
1.
2.
•
Quirks mode
Standards mode
The parse/render mode is
determined by the
<!doctype> statement
–
Recall this is called the
“doctype switch”
CSE 134B Web Client Languages
Inheritance – Trees in Use
• Elements inherit the rules of their enclosing parents. So given
p {color: #ff0000; font-family: Arial;}
then apply it to
<p>I expect this <b>to be red, Arial and bold</b> of
course</p>
• Of course just like real life trait inheritance sometimes you override
things
b {color: #00ff00;}
• Important Note: Not every rule inherits—think borders!
• Important Note: Don’t forget defaults! They inherit
too!
CSE 134B Web Client Languages
Trees in Use - Inheritance
CSE 134B Web Client Languages
Trees in Use - Inheritance
CSE 134B Web Client Languages
Trees in Use: Contextual Selection
•
Select descendents with a space in a rule
p strong {background-color: #00FF00;}
/* only strong elements descendents of a p element
•
*/
Contextual rules are often helpful when using specific id or class decorated
containers
– #navbar a {text-decoration: none;} /* all nav bar links
don’t need underline */
• You may find the wildcard selector * useful with contextual selectors
div * b
{background-color: yellow; }
• More commonly though we see the wildcard used to clear out global
defaults
* {margin:0;padding:0}
/* match everything
CSE 134B Web Client Languages
Advanced Tree Thinking
• Direct Child Selector
body > p {background-color: yellow;}
/* <p> tag must be directly enclosed
within the <body> tag. */
– Not the same as the contextual selector body p
which simply says that p must be a descendent of body
• Adjacent-sibling Selector
h1 + p {color: red;}
/* <p> tags directly after <h1> are red
<h1>Heading</h1>
<p>I would be red with this rule</p>
<p>I would not be red</p>
*/
CSE 134B Web Client Languages
Advanced Tree Thinking – CSS2 & 3
• CSS2-3 suggest a number of selectors that would rely
some solid tree understanding
– :first-child
– :last-child
– strong ~ em
/* the em preceded by the strong –
siblings not just adjacent */
– :empty
– :nth-child(n)
– :nth-last-child(n)
– :nth-of-type(n)
– :nth-last-of-type(n)
– And more…see http://www.w3.org/TR/2001/CR-css3-selectors20011113/#selectors
– Interesting note jQuery selector syntax
CSE 134B Web Client Languages
Attribute Selectors
• One interesting aspect of CSS2 is attribute based
selectors
– Occurrence Match
a[href]
{color: green;}
/* a tags with href green */
– Value match
a[href=″http://www.htmlref.com″]
{font-weight: bold;}
– Partial Match (space seperated)
p[title~=″test″] {font-style: italic;}
– Partial Match (dash separated)
p[lang|=″en″] {color: red;} /* matches en-uk, en-us */
CSE 134B Web Client Languages
Attribute Selectors in CSS 3
• CSS 3 indicates that it will support
– Substring
a[href$=“.edu“]
/* link to EDU site? – maybe not */
– Ending matches
a[href$=“.pdf“] /* pdf files */
– Starting matches
a[href^=“http“] /* offsite links */
• Already we see much of this implemented in standards
aware browsers allowing for interesting link direction
ideas
CSE 134B Web Client Languages
Pseudo Classes
• CSS1 supports the common link state selectors
– a:link
– a:active
– a:visited
• Most CSS1 compliant browsers also support a hover
state
– a:hover
– You should place hover rules after link and visited to avoid
cascading problems
– Beware of document reflow if you change size
– A pseudo class like :hover is not supposed to be specific to
links (though IE doesn’t like that so much) in many cases
CSE 134B Web Client Languages
Pseudo Classes in CSS2
Numerous pseudo classes in CSS2:
- :first-child
Relies on tree knowledge
- :focus
Useful for form field highlighting
- :lang
Useful in mixed-language pages
- :before
- :after
used primarily with content inclusion properties to
add graphics or text around sections
CSE 134B Web Client Languages
CSS 3 Pseudo Classes
• CSS3 adds in a few interesting pseudo selectors
like
- for checked elements
:selection – for selected text/objects
:enabled – enabled objects (ex. Form fields)
:disabled – disabled object (ex. Form fields)
:target – the target window/zone for a URL
– :checked
–
–
–
–
CSE 134B Web Client Languages
Pseudo-element Selectors
• Like pseudo classes these depend on content and
thus their effect varies
– :first-letter
p:first-letter {color: red;
font-size: larger;}
– :first-line
p:first-line
{color: gray;}
CSE 134B Web Client Languages
What Rule Wins?
• The basic idea is the more specific the rule the more power it has
– class rules beat element rules, but id rules beat class rules, and
so on
• Another way to think about things is the closer the rule to the tag
the powerful the rule is.
– Inline style beats a document wide style which beats a linked
style and so on.
• User styles always beat author styles
• No guessing is required there is a formula and of course your
browser’s developer tools show the application of rules in play
• If a particular rule should never be overridden by another rule, the
!important indication should be used.
p {color: red !important; font-size: 12pt;}
Example: http://www.htmlref.com/examples/chapter10/important.htmlml
CSE 134B Web Client Languages
Users Always Win!
CSE 134B Web Client Languages
CSS Measurements
• CSS provides rules to affect the spacing and layout of text including
word spacing, letter spacing, line height, horizontal and vertical
text alignment and indentation.
• CSS provides measurements in
–
–
–
–
–
–
–
–
pixels (px)
points (pt)
inches (in)
centimeters (cm)
millimeters (mm)
picas (pc)
em measurements (em) and ex measurments (ex)
Percentage values
• Most folks seem to use points or pixels despite the possibilities of
relative measurements.
CSE 134B Web Client Languages
CSS Properties
• Core Style Sheet Properties
– About 50 or so to learn in CSS1/2 and many more later
• Book or spec, you choose
• Specs and other info at http://www.w3.org/Style/
– Try to learn in categories (font, color, etc.)
– Short hand notations are possible
– Not consistent in browser support
– Be careful--even when supported there are problems
– There is a CSS validator at the W3C
• http://jigsaw.w3.org/css-validator/
CSE 134B Web Client Languages
Font Properties
• Font properties
– font-family – used to set to the font family used to render text.
– May be generic name (e.g. sans-serif) or specific font type (e.g. Arial)
– All browsers are supposed to support
• Serif (e.g. Times)
• Sans-serif (e.g. Helvetica)
• Cursive (e.g. Zapf-Chancery)
• Fantasy (e.g. Western)
• Monospace (e.g. Courier)
• Comma separate font names if user doesn’t have one
body {font-family: Arial, Helvetica, Sans-serif;}
CSE 134B Web Client Languages
Surprise - Browser Differences
CSE 134B Web Client Languages
Custom Fonts
• IE introduced custom fonts, Netscape did
something as well but they languished for years
without use.
• For a while it was hacky
– Font in image
– Image replacement
– Flash!
• Today we do not need hacky mechanisms
because browsers support downloadable fonts
but… trouble exists
CSE 134B Web Client Languages
Downloadable Font Basics
/* Define the font and then use it… follow it
with some built-in font */
@font-face {font-family: fontname;
src: url(fontfile);}
@font-face {font-family: "handwriting"; src:
url(handwriting.ttf);}
body { font-family: "handwriting", cursive;
font-size: 5em; }
Because of variations and serving issues many people like
using hosted services that address this concern
like Google Fonts or Typekit
CSE 134B Web Client Languages
Custom Fonts Work Cross Browser
CSE 134B Web Client Languages
Font Concerns
•
•
•
•
•
•
Font ownership
MIME types for delivery
Download/render time concerns
Ransom note design
Alternatives for fallback
Resource:
http://www.google.com/fonts/
CSE 134B Web Client Languages
Font Sizing
• font-size property
– Used to set the relative or physical size of the font
p {font-size: 18pt;}
strong {font-size: larger;}
h1 {font-size: 200%;}
– Some suggest only relative and percentage should be
used, but designers seem to favor the point and pixel
measurements despite their flexibility problems
– Direct font-size manipulation is becoming popular in site
toolbars
CSE 134B Web Client Languages
Font-sizing Cross-Browser Comparison
CSE 134B Web Client Languages
Font Style
• font-style
– Used to set normal, italic, or oblique style for the font in use
strong {font-style: italic;}
h2 {font-style: oblique;}
CSE 134B Web Client Languages
Font Weight and Variant
•font-weight
-used to select the weight or darkness of the font.
Values range from 100-900 with some relative and keyword values
also allowed though you will likely not have the granular that is
suggested by the values
strong
{font-weight: bolder;}
h1
{font-weight: 900;}
.special {font-weight: extra-bold;}
•font-variant
-used to set a variation of the current font.
Currently only small-caps and normal are possible variants
Small caps is the text in all caps but smaller than the surrounding
text
em {font-variant: small-caps;}
CSE 134B Web Client Languages
Font Property
•
The font property by itself serves as a short cut form and allows all fontproperties to be specified with one rule and also provides the line-height
setting which specifies the distance between two lines of text.
•
The generic form of the rule is
font: font-style font-variant font-weight font-size/line-height
font-family;
•
Examples
p {font: italic 900 28pt/200% ″Impact″;}
p {font: italic 18pt/24pt;}
•
Note that rules can be left out if not needed
•
Tip: Do not use short-hands at first. They are harder to debug.
CSE 134B Web Client Languages
Text Properties
• text-transform
– can be used to effect the capitalization of the text it is applied to.
– Possible values include capitalize, uppercase, lowercase, and none.
– Examples
p
{text-transform: capitalize;}
.lower
{text-transform: lowercase;}
– Note that the property value of capitalize results in all words
being capitalized not just the first one of a sentence.
– The value of transformation might be more related to
scripting?
CSE 134B Web Client Languages
Text Decoration
•text-decoration
-can be used to define an effect on text
-Standard values include line-through, overline, underline, and none
The value of blink is supported in some versions of Netscape.
-Examples
.struck {text-decoration: line-through;}
span.special
{text-decoration: blink;}
h1
{text-decoration: overline;}
a:hover
{text-decoration: none;}
Note: Commonly this is used with a tags to turn off underlines, but beware
usability concerns
CSE 134B Web Client Languages
Text Properties Contd.
• word-spacing
– Specifies the amount of space between words
– Distance between words can be specified in a variety of measurements:
• inches (in), centimeters (cm), millimeters (mm), points (pt), picas (pc), em
(em), x-height (ex) and pixels (px)
body {word-spacing: 10pt;}
• letter-spacing
– Specifies the amount of space between letters
– Same measurements can be used to specify distance between letters
p {letter-spacing: 0.2em;}
Question: Is this full kerning? Why or why not? Consider two kerning
pairs.
CSE 134B Web Client Languages
Text Properties Contd.
• text-align
– Determines how text in a block-level element is
horizontally aligned
– Allowed values are left, right, center,
justify
div {text-align: justify;}
/* be careful when using justify */
• text-indent
– Sets the indentation for text in the first line of a
block-level element
– Its value can be either a length (.5cm, 15px, 12 pt,
etc) or as a percentage of the width of the block
(10%)
p {text-indent: 2em;}
CSE 134B Web Client Languages
Text Properties Contd.
• line-height
– Sets the height between lines in a block-level element (known
typographically as leading)
– Its value can be either the number of lines (1.5), a length
(14pt, 20px, etc.), or percentage of the line height (200%, etc)
– Example for double-spacing:
p.double {line-height: 2;}
p.double {line-height: 200%;}
• white-space
– Controls how spaces, tabs, and newline characters are handles
in an element
– Possible values: normal, pre, nowrap
p.pre {white-space: pre;}
CSE 134B Web Client Languages
Vertical Alignment
• vertical-align
– Controls the vertical positioning of text and images
with respect to the baseline currently in effect.
– Possible values: baseline, sub, super, top, text-top,
middle, bottom, text-bottom, and percentage values.
.superscript {vertical-align: super;
font-size: smaller;}
• Example covering previous slides:
http://www.htmlref.com/examples/chapter10/text_properties.htm
l
CSE 134B Web Client Languages
Misc. CSS2 Text and Font Changes
• font-stretch is used to stretch or condense fonts and texts
values of ultra-condensed, condensed, expanded, etc. It also takes
relative values like wider or narrower
.narrow
{font-stretch: narrower;}
#arialstretch {font-family: Arial; font-stretch:
ultra-expanded;}
• font-size-adjust can be used to scale fonts to make content
take up similar space regardless of font availability.
– It is not well supported in browsers
• text-shadow allows us to create drop shadows on text
h1 {color: #CC0000; text-shadow: 0.2em 0.2em blue;}
– Likely to be the new <blink> but so far only the very latest version of
Safari supports this property
CSE 134B Web Client Languages
List Properties
• list-style-type sets the type of the list numbering or bullet for
<ol> and <ul> lists respectively. This property would be
equivalent to the type attribute found in (X)HTML.
• Allowed values include decimal, lower-roman, upper-roman,
lower-alpha, upper-alpha, disc, circle, square, and
none.
ol.roman
ul
ol ol
{list-style-type: upper-roman;}
{list-style: square;}
{list-style-type: lower-roman;}
CSE 134B Web Client Languages
List Properties Contd.
• list-style-image can be used to set the bullet to an image
ul {list-style-image: url(colorball.gif);}
• list-style-position can be used to set where the labels for the list
are positioned relative to the box/block that makes up the list. The
allowed values are inside and outside
ul.compact
{list-style-position: inside;}
• list-style is a short hand notation that allows all the aspects of the list
to be set at once.
ul {list-style: inside url(bullet.gif);}
• List notes – while not CSS specific note that semantically the various list
tags are often used in markup to define navigation menus which are styled
with display, background, hover, and other properties to create menus
CSE 134B Web Client Languages
List and Counting Changes in CSS2
• Main change is the use of counters to control list numbering though
there are now more list types for Japanese and other languages
• With counters you can increment/decrement depending on certain
conditions and create outline styles.
• The counter, counter-increment, and counter-reset properties are
used to set variables to control the counter value. In some sense we
see CSS introducing some simple programming concepts.
<style type="text/css">
p {counter-increment: par-num;}
h1 {counter-reset: par-num;}
p:before {content: counter(par-num, upper-roman) ". " }
</style>
CSE 134B Web Client Languages
Counter Rendering
CSE 134B Web Client Languages
Colors
• Color can be specified in numerous ways
1. Color names: 16 names like Black, Blue, Green, Navy, Red, Silver, etc.
2. Hex forms in #RRGGBB form like #FF0033 and #rgb like #0f0
3. RGB form rgb(R, G, B) where the values of R, G, and B range from 0 to 255.
Example rgb(255, 0, 0) for pure red.
4. CSS3 define an RGBa extended form which also allows opacity as the 4th value –
semi-transparent blue for example rgba(0,0,255,0.5)
5. CSS3 defines hue-saturation-lightness values - hsl(0, 100%, 50%) is the example
for red
•
Note: Only defined names and normal #RRGGBB hex or basic #RGB format should be
used as browser worries still abound.
CSE 134B Web Client Languages
Setting Colors
• The color property can be used on any element
to set text color
• Examples
body
h1
.fun
{color: green;}
{color: #FF0088;}
{color: #0F0;}
Note: If you are CSS validating you will get complaints
if you are not explicit when setting colors or
backgrounds to avoid accidental mask out.
CSE 134B Web Client Languages
Background Properties
• background-color property is used to set an element’s
background color and can take a color value or the keyword
transparent
p
body
{background-color: yellow;}
{background-color: white;}
• background-image property is used to set a background image
for any element.
#krispy
{background-image: url(donut-tile.gif);}
• Transparent regions will show the background so this may be
combined with background-color
p
b
{background-image: url(donut.gif);
background-color: white;}
{background-image: url(bricks.gif);}
CSE 134B Web Client Languages
Background Properties Contd.
• background-repeat
– property is used to determine how a background image tiles when it is
smaller than the region it is used in.
– Default action is repeat, but repeat-x can be used to tile only
horizontally and repeat-y only vertically. A value of no-repeat can
also be used.
– Example:
p {background-image: url(tile.gif);
background-repeat: repeat-x;}
body {background-image: url(tile.gif);
background-repeat: no-repeat;}
CSE 134B Web Client Languages
Background Properties
• background-attachment
– can be set to limit if a background should be fixed or scroll.
body {background-image: url(tile.gif);
background-repeat: no-repeat;
background-attachment: fixed;}
– Fixed position stays put as content scrolls over it
CSE 134B Web Client Languages
Background Properties
• background-position
– is used to specified where a background image should be positioned.
– Keywords and absolute positions can be used. In conjunction with
foreground position it is no possible to control pages down to the pixel
p {background-image: url(picture.gif);
background-position: 10px 10px;}
CSE 134B Web Client Languages
Background Property
• Like the font property, the background property provides a
shorthand notation for setting many background properties at
once.
• Order does not matter with this property
p {background: white url(picture.gif) repeat-y
center;}
b {background: yellow;}
CSE 134B Web Client Languages
Box Properties
• Some elements are block (or if it is easier to think of box). For
these we can control their renderings including margins,
borders, padding, and so on. The document itself is a box too!
CSE 134B Web Client Languages
Watch How You Measure
When setting object size to add or subtract as we set the box margins,
border and padding?
CSE 134B Web Client Languages
In Ye Olden Days
• This actually was a problem
CSE 134B Web Client Languages
Fixing the Sizing Bug
• Parser tricks “ex: box model hack”, conditional
comments, JavaScript
– Some of these are awful and we hope go away
• But…the rub is it was an legitimate question
about how to measure and interestingly will be
settable (or already is) with a property
–
–
box-sizing: border-box | content-box | inherit
The default content-box defines that element size is defined by adding the border, padding,
and height/width together to define the size of the box which is what is typically seen in
browsers. When set to border-box a supporting browser will render the box by the defined
height and width properties pulling the border and padding size from within the box similar
to much older box model thinking.
CSE 134B Web Client Languages
Margins
• margin, margin-top, margin-right, margin-bottom,
margin-left properties
•
You can set margins individually or you can set them with a short-hand that flow
clockwise from the top value and copies values to the opposite side if not specified
#p1 {margin: 5px;}
/* 5px on all sides */
#p2 {margin: 5px 10px;}
/* 5px on top-bottom, 10px left and right */
#p3 {margin: 5px auto 10px;}
#p3 {margin-top: 10px; margin-bottom: 20px;
margin-left: 30px; margin-right: 50px;}
•
Negative margins can be used for interesting effects, but be carefully about clipping
p {margin-left: -2cm; background-color: green;}
CSE 134B Web Client Languages
Box Properties Contd.
• Borders can be put around elements. Primarily you will place this
on blocks (paragraphs, etc.)
• border-style is used to set the type of border and may be
dotted, dashed, solid, double, groove, ridge, inset, and outset.
– Watch out for support!
h1{border-style: solid;}
p.boxed
{border-style: double;}
• Recall that border is a property that doesn’t inherit
• Other border properties: border-width, border-color
p.thickandthin {border-width: thick thin; border-color:
red;}
CSE 134B Web Client Languages
Padding, Height and Width
•
Padding can be set to specify the space between the element’s border and its
contents. You can set all sides with the padding property or each on
separately with padding-left, padding-top, and so on.
div
{padding-top: 30px;}
p {border-style: solid: padding: .5cm;}
•
You can set the height and width of an element with the properties named
appropriately enough height and width
•
These are usually absolute measurements like px, in, cm, etc. However, you
can use percentage values or others as well.
#image1 {height: 10cm; width: 10cm;}
CSE 134B Web Client Languages
float and clear
• It is possible to “float” block elements using the float property.
This allows text to wrap around the block element. Allowed
values are left and right
img.logo {float: right;}
#p1 {height: 100px; width: 100px; float: left;}
• Just like (X)HTML because you can float things you need an
extension to <br> like clear=“left”. CSS provides the clear
property to deal with this.
p.clearit
.clearall
{clear: left;}
{clear: all;}
CSE 134B Web Client Languages
Display Property
•
(X)HTML elements fall into a few different categories like block, inline, list,
misc., and so on.
•
CSS provides a way to control the meaning of a particular element and its
display properties
•
The display property can be used to control the type of element. Allowed
values include
• none - not only invisible but doesn’t take up window space
• block - can be used to turn an element into a block element
• inline - turn an element to an inline form
• list-item - turn an element to an inline
CSE 134B Web Client Languages
Display Property Changes in CSS2
• The little used display property now takes new values including:
compact, run-in and marker.
<h1 style="display: run-in">Heading 1</h1>
<p>This paragraph should have the heading run right
into its first line.</p>
• The marker value is interesting because it allows the automatic
inclusion of flagged elements
#new:before
{display: marker;
content: url(new.gif);
marker-offset: 1.5em; }
• There are even more display values related primarily to tables but
even the basic values presented are very poorly supported so far.
CSE 134B Web Client Languages
Positioning and Sizing of Regions
• CSS-P has been incorporated into the CSS2
specification
– position property has the following values, used to
specify the position of an element :
static (default, takes position from the document flow)
absolute (most common)
relative (valuable with nested objects)
fixed (very interesting but Mozilla / Opera only L without
fixes usually done in JS )
• inherit (take your parent’s value)
•
•
•
•
CSE 134B Web Client Languages
Fixed Positioning Notes
• Fixed positioning would be quite useful for
pegging navigation, unfortunately it doesn’t
work in IE6 or before without fixes
• One possibility is to use a library for example
the IE7 JS library
http://code.google.com/p/ie7-js/
• Other less JS focused possibilities
http://tagsoup.com/cookbook/css/fixed/ tend
to use CSS hacks of varying quality
• Fortunately later IEs address this
CSE 134B Web Client Languages
z-index and Stacking Order
– z-index property
• Used when elements overlap one another
• Tip: Avoid using values like 1,2,3 try using 5,10,15 or larger
gaps. It allows for putting items in between
• When z-index is not set the order in which the tag is
encountered in the document determines the stacking value.
The later in the document the higher up z-index wise it will
be
CSE 134B Web Client Languages
Visibility
• visibility property
– Determines whether an element is visible, values are
visible, hidden and inherit.
– Beware this is not the same as display: none
which completely removes the tag from the document
flow.
– Careful
<p>This is a <span style=“display:
none”>test</span> of the two <span
style=“visibility:
hidden;”>properties</span>. You should
notice a difference</p>
CSE 134B Web Client Languages
Overflow
– The overflow property determines what should happen when
content doesn’t fit in its allocated space defined by height and
width properties
• Possible values: hidden, scroll, none
• Scroll introduces a similar feature to <iframes>
• Be careful of printing scrolled regions
CSE 134B Web Client Languages
Max and Min Height and Width
• max-width and max-height properties can be set to
indicate how large a region can grow when the browser
is resized
• min-width and min-height can limit how far down a
region can shrink
#p1 {width: 50%; min-width: 200px;
max-width: 400px;}
• Example: minmaxwidth.html
• Note: browser support is inconsistent pre-IE7/Firefox,
though some folks have tried to use JavaScript to
dynamically adjust regions to suit
CSE 134B Web Client Languages
Min/max-width Problem
• Good news newer IE supports it
• You can back fix some browsers with JavaScript – see
http://www.doxdesk.com/software/js/minmax.html as one example
• There are certain CSS hacks as well at least for height with varying quirks
CSE 134B Web Client Languages
Clipping Regions
• The clip property can be used to set the coordinates of a clipping
rectangle
–
A clipping rectangle defines the subset of the content rectangle that actually
shown
• Syntax
clip: rect(top right bottom left);
• Example
<div style="position:absolute;
background-color: #FFA500;
left:20px; top:20px;
width:140px; height:140px;
border-style: solid; border-width: 1px;
clip: rect(10px 90px 90px 10px);" >
With clipping
</div>
CSE 134B Web Client Languages
Clipping Example
• Clipping is best shown when you can see that it limits
the content showing as demonstrated by this picture
CSE 134B Web Client Languages
User Interface Changes Start in CSS2
• The cursor property can be used to set cursors.
–
–
–
Usually used with :hover or JavaScript mouseover
Values for built-in cursors like pointer, text, crosshair, nw-resize, s-resize, wait,
etc. are fairly well supported
Internet Explorer 6 also was the first to allow for custom cursors without a plugin or control
• p {cursor:url("mything.cur"), url("second.cur"), text; }
• Notice the fall-thru technique for problems
• Another major change is the use of system dependent color values
so you can match a Web interface to a user’s GUI preference.
– Points to the future where the difference between a Web application
and a desktop application is mainly if it is installed locally or not
CSE 134B Web Client Languages
Browser Based CSS Changes
• zoom property allows you to zoom text/objects up and
down
– <p onmouseover="this.style.zoom='200%'"
onmouseout="this.style.zoom='normal'">
Roll your mouse over me and watch me zoom!</p>
• Scrollbar control to color scrollbars
– Example: body {scrollbar-face-color: red;}
– Be careful with a strict doctype you might see these properties
ignored by IE even!
• Mozilla has *tons* of changes as well! Fastforward to today and CSS features explode with
browser prefixing –webkit, -ms, -moz, etc.
CSE 134B Web Client Languages
Hacking Around in CSS
• Given browser quirks there are a number of
general techniques used to address problems
1. Using features that only one browser or another can
support (ex: @import) as a way to partition rules
2. Causing a parse error in some browsers to hide rules
that may follow (ex: voice-family tricks)
3. Using IE explorer conditional comments
4. Using JavaScript
•
•
Detection with alternate style sheets
Patching to add a feature or make complaint
CSE 134B Web Client Languages
Normalization and Adopting Frameworks
•
What would this rule do?
* {margin: 0}
•
We might imagine an approach were we normalize
various measurements or defaults for browsers to make
it much easier to work CSS, such techniques are better
than hacking around
–
•
Example: YUI Reset http://yuilibrary.com/yui/docs/cssreset/
We see a number of libraries helping us layout and
address CSS concerns today
http://twitter.github.io/bootstrap/
http://foundation.zurb.com/
CSE 134B Web Client Languages
CSS3 Menu of Fun!
CSE 134B Web Client Languages
CSS3 Menu Contd.
CSE 134B Web Client Languages
CSS3 Menu Contd... (and on and on)
CSE 134B Web Client Languages
CSS3 Reality
• Some of these are dead (ex. Hyperlink)
• Some of these are very active (ex. 2d
transforms)
• Some are already implemented in browsers
• Some things thought to be CSS3 really aren’t
(yet), just vendor innovation awaiting a formal
submission
• This stuff moves fast and not…some CSS3
features have been behind browser flags for 5+
years now
CSE 134B Web Client Languages
New Units
Measurement
Description
Example
A font-related length that is equivalent to the #swiss
ch
width of the character 0 (zero) in the current font.
{font-size: 4ch;}
deg
Degrees
transform: scale(1.0) rotate(0deg);
dpcm
Dots per centimeter
@media print and (resolution: 100dpcm) { }
dpi
Dots per inch (used in media queries).
@media print and (resolution: 300dpi) {
Hz
Hertz
#barrywhite {pitch: 70Hz;}
kHz
Kilohertz
#treble {pitch :6kHz;}
ms
Milliseconds
#a1 {transition-property: color;
transition-duration: 500ms;}
rad
Radians
#voiceAbove {elevation: 50rad;}
rem
The font size of the document’s root element.
#innerP {font-size: 1.5rem;}
s
Seconds
#a2 {transition-property: color;
transition-duration: 1s;}
vh
A value relative to the viewport’s height. The full
.halfHeight {width: 50vh;}
viewport height is 100vh.
vm
Either the viewport’s height or its width, whichever
#halfBox {height: 50vm; width: 50vm;}
is smaller. The minimum value is equal to 100vm.
vw
A value relative to the viewport’s width. The
viewport’s full width is 100vw units.
.halfWide {width: 50vw;}
}
CSE 134B Web Client Languages
New Color Values
• HSL color - Hue Saturation Lightness values are specified as
hsl(hue,saturation,lightness).
– Hue is set as the degree on the color wheel, 0 or 360 if you
wrap around is red, 120 is green, and 240 is blue, with the
various other colors found between.
– Saturation is a percentage value, with 100% being the fully
saturated color.
– Lightness is a percentage, with 0% being dark and 100% light with
the average 50% being the norm.
– #red {color: hsl(0,100%,50%);}
CSE 134B Web Client Languages
New Color Values
• Alphas added in HSLa, RGBa
• 0 (fully transparent) – 1 (fully opaque)
#bluetrans
{color:hsla(240,100%,50%,0.5);}
#redtrans {color:rgba(255,0,0,0.4);}
/* fallback with declaring rgb,
then rgba */
• transparent keyword
– Same as rgba(0,0,0,0)
<p style="color: transparent; ">When working
seems invisible</p>
– currentColor keyword
CSE 134B Web Client Languages
Selector Explosion
• Huge change mostly in place
• May be abused
– Example - :not(selector)
*:not(h1) {color: black;}
/* sets the color to black on every element that is not
an h1 tag */
• Familiar to users of jquery
• ~ - Sibling selector
p ~ strong {font-style: italic;}
/* sets the font style to italic on all strong tags that
have a p tag as a preceding sibling */
CSE 134B Web Client Languages
Important Syntax Change
• : becomes :: to differentiate a pseudo class with
a pseudo element
– ::after, ::before, ::first-letter, ::first-line
CSE 134B Web Client Languages
More Selectors
• Attribute Matching Improvements
– Start with - E[attr^=value]
p[title^="HTML"]{color: green;}
/* set color green if title starts with HTML */
– End with - E[attr$=value]
p[title$="!"]{color: red;}
/* sets color to red if title ends with ! */
– Contains - E[attr*=value]
p[title*="CSS"]{font-style: italic;}
/* sets the font style to italic in any p tag that
has CSS in its title */
CSE 134B Web Client Languages
Tree Selectors
• :first-of-type
strong:first-of-type {font-size: bigger;}
/* sets the font size bigger on the first strong tag of
its parent */
• last-of-type
strong:last-of-type {font-size: smaller;}
/* sets font size smaller on the last strong
tag of its parent */
• :last-child
p:last-child {font-size: small;}
/* sets the font size to small on the p tags
that are the last child of their parent */
CSE 134B Web Client Languages
Tree Selectors
• :nth-child(n)
div:nth-child(2) {background-color: red;}
/* sets the background color to red if the div is
its parent’s second child */
• :nth-last-child(n)
p:nth-last-child(3) {color: yellow;}
/* sets the color to yellow if the p element is its
parent’s third to last child */
• :nth-of-type(n)
strong:nth-of-type(5) {text-decoration:
underline;}
/* underlines the fifth strong tag under a parent */
CSE 134B Web Client Languages
Tree Selectors
• nth-last-of-type(n)
p:nth-last-of-type(2) {color: purple;}
/* sets the color to purple on the second to
last p element of its parent */
• :only-child
h1:only-child {color: blue;}
/* sets the h1 color to blue if the h1 is the
only child of its parent */
• :only-of-type
p:only-of-type {font-weight: bold;}
/*sets the p element to be bold if it is the
only p tag child of its parent */
CSE 134B Web Client Languages
Tree Selectors
• :root
:root {background-color: blue;}
/* sets the background color to blue for
the root element */
CSE 134B Web Client Languages
API states
• :checked, :default, :disabled, :enabled
• Emerging: :optional, :read-only, :out-of-range, :inrange. :invalid, :valid, :required
– Useful for HTML5 Form validation
• ::selection
#test::selection {color: red; background-color:
yellow;}
/* makes the text red with a yellow background
when selected */
• :target
:target{color:red;}
/* if the element is the target of the referring
URI, the color is set to red - :: ? */
CSE 134B Web Client Languages
Media Queries
• A media query use the media attribute and extends
it to conditions
– “This CSS only if this criteria met”
– Avoids needing JS
<link rel="stylesheet" media="screen and
(min-width: 1024px)" href="wide.css">
<link rel="stylesheet" media="screen and
(min-width: 641px) and (max-width:
1023px)" href="medium.css">
<link rel="stylesheet" media="screen and
(max-width: 640px)" href="narrow.css">
CSE 134B Web Client Languages
Media Queries Contd.
http://htmlref.com/ch6/mediaquery.html
CSE 134B Web Client Languages
Media Queries Contd.
• Common values
– aspect-ratio, device-aspect-ratio
– orientation
– height, width, device-height, device-width
• resolution
– color, monochrome
• This is likely detectable with JS already
CSE 134B Web Client Languages
Multiple Column Support
• Lots of properties for setting
• column-count: integer | auto
• column-rule: rule-width rule-style
color
• column-gap: length | normal
• Do multiple columns make sense,
especially without a fixed height?
– Maybe if not wrapped
CSE 134B Web Client Languages
Column Demo 1
http://htmlref.com/ch6/columncount.html
CSE 134B Web Client Languages
Column Demo 2
http://htmlref.com/ch6/columnrule.html
CSE 134B Web Client Languages
CSS Rounded Corners
• Previously hacked using “corner” image(s)
• Now border-radius can be used to control
border curvature
#div1 {border: 1px solid black; border-radius: 15px;}
• Like most CSS3 features vendor specific
prefixes are used -webkit- , -moz- , and so
on
CSE 134B Web Client Languages
border-radius Example
http://htmlref.com/ch6/borderradius.html
CSE 134B Web Client Languages
border-radius Notes
• Individual border corners can be set
•
•
•
•
border-bottom-left-radius
border-bottom-right-radius
border-top-left-radius
border-top-right-radius
• Some quirks exist here with syntax variations
in some browser versions -moz-borderradius-topleft
CSE 134B Web Client Languages
border-image
CSE 134B Web Client Languages
border-image contd.
http://htmlref.com/ch6/borderimage.html
CSE 134B Web Client Languages
box-reflect
http://htmlref.com/ch6/boxreflect.html
CSE 134B Web Client Languages
box-shadow
• Set a shadow for a box element
– box-shadow: shadow1 [,..shadowN]
• where shadow is
– color x-offset y-offset blur-radius spread-radius
CSE 134B Web Client Languages
box-shadow Example
http://htmlref.com/ch6/boxshadow.html
CSE 134B Web Client Languages
CSS Gradients
• A CSS gradient image that can be used anywhere an
image URL is required, including background-image,
border-image, and list-style properties
•
<div style="height: 300px; width: 200px;
padding: 20px;
border: 5px solid black;
background: -webkit-gradient(linear,
left top, left bottom, from(#f00),
to(rgba(0,255,0,0)), color-stop(.5, #00f));" ></div>
<div style="height: 300px; width: 200px;
padding: 20px;
border: 5px solid black;
background: -webkit-gradient(radial, 100
100, 20, 200 200, 50, from(#ff0),
to(rgba(255,0,255,0)), color-stop(25%, #f00));"
></div>
CSE 134B Web Client Languages
CSS Gradients
http://htmlref.com/ch6/gradient.html
CSE 134B Web Client Languages
text-shadow
http://htmlref.com/ch6/textshadow.html
CSE 134B Web Client Languages
text-stroke
http://htmlref.com/ch6/textstroke.html
CSE 134B Web Client Languages
Getting Off Track?
• Animations
– http://htmlref.com/ch6/animation.html
• Transforms
– Page 714
• Transitions
– http://htmlref.com/ch6/transition.html
• Seem to be blurring the line again
• Other thoughts on the potential for trouble or
useful changes like variables
• Preprocessors! Less, Sass, Stylus
CSE 134B Web Client Languages
Why Bother Just Use Bootstrap?
• The complexity of CSS has lead to many
developers just employing a toolkit such as
Bootstrap and setting the appropriate class
names
– Good: Easy, Consistent UI, Productivity High!
– Bad: Sameness, Download Bloat, Divitits, Has become
its own convention and legacy
• Tools and frameworks are fine but we should
judge on correctness and against our constraints
(speed, maintenance ease, etc.) For us we are
going to say mobile first and speed speed speed!
© Copyright 2026 Paperzz