Introduction to Cascading Style Sheets Tutorial Booklet for LSC 610 – Catholic University By Ran Hock Copyright © 2007 by Randolph Hock, Ph.D. Ran Hock 9919 Corsica Street Vienna, VA 22181 USA ran@onstrat.com 001-703-242-6078 1-800-871-4033 www.onstrat.com 102407 Introduction to Cascading Style Sheets Table of Contents INTRODUCTION TO CASCADING STYLE SHEETS .............................................................................................................1 WORKSHOP OBJECTIVES .........................................................................................................................................................1 LEVELS AT WHICH STYLES CAN BE APPLIED...................................................................................................................4 PREPARING YOUR HTML PAGES ...........................................................................................................................................5 THE FORMAT OF STYLES .........................................................................................................................................................6 SELECTORS ...................................................................................................................................................................................7 INHERITANCE AND PRECEDENCE.......................................................................................................................................10 COMMON, MOST USEFUL, STYLES ......................................................................................................................................13 FONTS AND TEXT ......................................................................................................................................................................14 MARGINS......................................................................................................................................................................................16 BACKGROUNDS..........................................................................................................................................................................19 POSITION .....................................................................................................................................................................................21 DYNAMIC EFFECTS ..................................................................................................................................................................23 COMMENTS .................................................................................................................................................................................24 RESOURCES.................................................................................................................................................................................25 INDEX ............................................................................................................................................................................................26 i Introduction to Cascading Style Sheets ii Introduction to Cascading Style Sheets Introduction to Cascading Style Sheets Sheets Just as anyone involved in any way with Web site design and management profits by knowing the basics of HTML, the same is now true of CSS (Cascading Style Sheets). Effective utilization of CSS can make the difference between an amateurish-looking site and a truly professional-looking site, gives far superior control of layout, makes it possible to change every page of your site in just seconds, and does things HTML just cannot do. This booklet will cover the basic structure of CSS styles and style sheets and how and where to apply them. A basic knowledge of HTML will be assumed. Booklet Objectives This booklet will help students: Know what CSS is all about and why it is useful Be able to construct styles Be able to apply styles at the inline, page and style sheet levels Be acquainted with the most common and useful specific styles 1 Introduction to Cascading Style Sheets What is CSS? CSS? Cascading Style Sheets “Style Sheets” are a concept that goes way back Editorial Styles – MLA, APA, Chicago, etc. “Cascading” The styles you define cascade down, allowing you to apply a style at a top level (e.g., a style sheet for your whole site) and have it automatically cascade down throughout your entire site, or at a page level and have it cascade down, etc. Developed and defined by the W3C – World Wide Web Consortium W3C - CSS Level 1 – Dec 1996 CSS Level 2 – May 1998 CSS Level 3 – Under Construction Styles – What they look like background-color: #FFFFFF; margin-top:20px; margin-left:50px; margin-right:70px; font-size:10px; font-family: Arial, Helvetica, sans-serif; width:750px; Style Sheets – What they look like CSS works best with well-structured, compliant, XHTML pages 2 Introduction to Cascading Style Sheets What Can CSS Do For You? More and easier control Change an entire site in a matter of seconds Precise locations of elements More options for individual tags More options (properties) For example: HTML Borders CSS Borders width width style (none, dotted, dashed, solid, double, groove, ridge, inset, outset, inherit) color spacing apply these values to each specific side of the border color (maybe) Can easily separate content from format Leaves content to HTML – CSS determines the “appearance” Makes universal changes possible Allows for designing for different formats (Web, print, mobile, etc.) Greater consistency with the latest version of HTML For example, deprecation of the <font> tag 3 Introduction to Cascading Style Sheets Levels at Which Styles Can Be Applied 1. Style Sheet (External Style Sheets) In an “external” Cascading Style Sheet file Can apply to an entire site 2. Style Element (Internal Style Sheets) In the heading of a specific webpage. <html> <head> <style type=text/css> h1 {color: blue;} p {font-family: arial;} </style> </head> <body> 3. Style Attribute (In-line Styles) Style as an attribute of an HTML tag <p style=”text-align: center”>The meaning of Life”</p> 4 Introduction to Cascading Style Sheets Preparing Your HTML Pages ages For best results, use XHTML Major differences between XHTML and HTML (really easy) In XHTML: Don’t leave out any <html> <head> <body> tags or <doctype . . . > Don’t capitalize the tags - <h1> not <H1> Put all attribute values in quotation marks - (border=”2”) not (border=2) Always have a closing tag. For every <p>, have a </p> <br /> not <br> All attributes must have an explicitly stated value noshade=”noshade” not noshade Structure the content of your page to identify portions to which you may want to apply styles. Most of this you can do after-the-fact, but it’s often easier to do it when you create the page, particularly creating divisions Divisions <div id=” ”> for major sections of the page e.g., <div id=”menu”> In the CSS, you will often refer to the id “names” you establish. “id”s refer to a unique element, can only occur once. No two elements can have the same id. Classes Whereas only one element, for example, a division, can have the name “menu” you can apply a class over and over. If throughout your pages you may often want to have something in red italics, identify those sections as a class, whenever you get the urge. <p class=”fancy”> <h2 class=”fancy”> Spans “Inline” spans are used to identify small sections of a page, particularly text. <span class=”quotations”> Wagner's music is better than it sounds.</span> 5 Introduction to Cascading Style Sheets The Format Format of Styles Constructing Style Rules: Selectors, Properties and Values Selector h1 Declaration {color: blue;} _________ ______ {Property: Value;} The selector identifies the HTML element(s) to which the rule will apply. The declaration identifies what is to be done to that element(s). The property is the feature you want to change. The value is how you want that to appear. Spacing is flexible, but the above is what you will usually see, for clarity. The semicolon is not actually required in this instance, but is used if another declaration is to be added. For example: h1 {color: blue; font-style: italic;} Most people put it in every time anyway, lest they forget it when they need it. 6 Introduction to Cascading Style Sheets Selectors Tag Selector Applies to an HTML tag h1 {color: blue;} Multiple selectors (Groups of Selectors) Applying the same rule to multiple selectors h1, p {color: blue;} ID Selector Applies to the particular, single, part of the page to which you have applied an “id” attribute. A pound sign indicates the id. Example of the corresponding HTML code: <div id=”main”> #main {color: blue;} Class Selector Applies to all elements to which a specific class has been assigned, using the HTML “class” attribute A period indicates a class. Example of the corresponding HTML code: <p class=”citation”> .citation {color: blue;} Selectors by Context Applies to elements within another specific element. For paragraphs within the “main” div, the following would make text in each paragraph red. #main p {color: red;} Pseudo-Class Selector Applies to elements that can’t be marked manually, such as the status of a link a:visited {color:red;} 7 Introduction to Cascading Style Sheets Cascading Style Sheets Construct them using a text editor, such as Notepad. Structure Often, but not necessarily, begins with an identifying comment /* stylesheet.css */ Rules are then listed. For clarity: Usually, the selector, and perhaps the opening brace, { , are on one line. Followed by each declaration Followed by the end brace, then, on a new line, the next selector For example: 8 Introduction to Cascading Style Sheets Link Your Pages To Your Style Sheet For each page to which you want the stylesheet to apply: In the head of the HTML page, add the “link” tag with an href that will lead to the stylesheet: href="cua.css" plus a “rel” attribute indicating the relationship: rel="stylesheet" and a “type” attribute indicating the type of content or media: type="text/css" For example: <link href="cua.css" rel="stylesheet" type="text/css" /> Viewing Other People’s Style Sheets – CSS Voyeurism A good way to explore the possibilities. For example, for www.infotoday.com, In your browser, View > Source Then go to the URL indicated by the location of the style sheet, e.g., www.infotoday.com/default.css 9 Introduction to Cascading Style Sheets Inheritance and Precedence Styles can happen to an element automatically because of inheritance When rules bump into each other, there are orders of precedence Inheritance For “nested” elements, rules usually are applied automatically because of “inheritance”. (They “Cascade”) Determines what happens if no specific style is applied to a particular element. <body> <div> <p> Here, <body> is a parent of <div> The <div> is a “child” of <body> <p> is a child” of <div> <div> and <p> are both “descendants” of <body> Unless another rule intervenes: Styles applied to the parent are usually inherited by the child and by other descendants If a style rule makes the body text Arial, the text in div and p will also be Arial. Precedence Determined by Specificity and Location Specificity The more specific rule wins. Take an example where the following rules exist: (inherited rules) body {color: red} .names {color: green} h1.names (color:purple} #menu {color: teal These are listed in increasing order of specificity: - (Inherited rules are over-ruled by any specific rule.) - For text in the body, but not with a “names” class, text will be red. - Text in an element with the class “names” will be green, since class is more specific than body. - h1’s within something with a class of “names” is more specific than just being in the class, so in those instances, purple will win. - IDs are considered most specific, since they are unique in a document. 10 Introduction to Cascading Style Sheets Location If two rules have equal specificity, the one that is stated later wins: Rules in a style sheet are overruled by Rules in the head of a webpage (Internal style sheet) are overruled by Local (inline) rules In other words: The rule closest to where it is being used will be the one that wins. 11 Introduction to Cascading Style Sheets CSS Color Options Colors in CSS can be specified in the following ways: Name The sixteen predefined HTML colors, black silver gray white maroon red purple fuchsia green lime olive yellow navy blue teal aqua {color: navy;} Probably will work by name: The 147 Scalable Vector Graphics Color Names {color: cornflowerblue;} See: SGV Named Color Codes at www.december.com/html/spec/colorsvg.html Six –Decimal Hexadecimal - #RRGGBB {color: #F8C473;} RGB using decimals (0-255) {color: rgb(176,48,96)} RGB using percents of RGB {color: rgb(50%,70%,90%)} And Other Ways See Color Definitions Chart at www.december.com/html/spec/colordef.html 12 Introduction to Cascading Style Sheets Common, Most Useful, Useful, Styles Font and Text Margins Borders Links Backgrounds Position Comments And Several More Along the Way 13 Introduction to Cascading Style Sheets Fonts Fonts and Text Family, size, weight, style, line height, text align and indent Can apply to paragraphs, headings, tables, etc. The HTML font tag is now deprecated! font-family p {font-family: Arial;} Allowing for alternate font faces: p {font-family: “Arial Black”;} p {font-family: “Arial Black”, Verdana, sans-serif;} font-size p {font-size: 180%;} p {font-size: 28px ;} p {font-size: x-small;} Can be expressed in the following ways pixel, % keywords – xx-small, x-small, small, medium, large, x-large, xx-large point, pica (use only in style sheets for print output) em (bolded. e.g., 1.5em) font-weight p {font-weight: bolder;} Values – normal, 100-900, bold, bolder, lighter font-style p {font-style: italic;} Values: italic, oblique, normal (italic and oblique are almost the same thing, the former created by a font designer, the latter created by the computer by slanting the text.) 14 Introduction to Cascading Style Sheets line height amount of space between each line in a paragraph p {line-height: 170%;} p {line height: 32;} Values – %, absolute value in pixels, etc. text-align p {text-align: center;} Values – left, right, center, justify text-indent p {text-indent: 20px;} p {text-indent: 1.5em;} Values – pixels or em’s (“em” is a “multiplier” of the text’s normal size.) text-decoration td text-decoration:none; Values – none, underline, overline, line-through, blink, inherit 15 Introduction to Cascading Style Sheets Margins This is one of the most useful features that CSS provides in a far more powerful way than does plain HTML. Apply it to the body, paragraphs, divs. etc. body {margin: 20px;} body {margin: 15%;} body {margin-top: 15px:} body {margin-bottom: 15px:} body {margin-left: 15px:} body {margin-right: 15px:} body {margin-top: 15px:} Values: pixels or percent of parent element margin: with one value, i.e. the first example above, applies to all four sides. With two values, they apply to top/bottom and left/right. With three values, they apply to top, right/left, and bottom. With four values, they apply to top, right, bottom, left.. Padding Padding is space around the contents of an element (comparable to cellpadding in HTML). {padding: 20px;) Different amounts around each side can be done by specifying numbers for top, right, bottom, left: {padding: 20px 10px 20ps 40px;) td {padding:10px 5px 10ps 0px;) 16 Introduction to Cascading Style Sheets Borders orders As with margins, CSS provides border features that HTML cannot. Can apply to any HTML tag. Can specify border style, color, width border-style {border-style: dotted;} Values: none, dotted, dashed, solid, double, groove, ridge, inset, outset. border-width {border-width: 5px;} border-color {border-color: red;} These can all be dealt with at once by use of border: followed by values for style, width and color (not necessarily in that order and not necessarily all three). {border 10px outset green;} The above examples will apply to all four borders. To apply rules to the four sides individually, use: border-left, border-right, border-top, and border-bottom {border-left: 3px outset blue;} 17 Introduction to Cascading Style Sheets Links Styles can be applied to links, based on the status a:link - for links not yet visited a:visited - for links that have been visited a:focus - for links that have been highlighted (by tabbing) a:hover - for links while the mouse is over them a:active - for links as they are clicked The above are referred to as “pseudo-classes” since they cannot be marked in your code, but instead have a variable status. a:link {color: red;} a:hover {color: orange;} a:hover {color: red; font-size: 180%;} 18 Introduction to Cascading Style Sheets Backgrounds In CSS, “background” refers to the background for a specific element (not for the overall page). h3 {background-color: yellow;} Values: a color, transparent, or inherit transparent lets the parent element’s background show through .hilights {background: yellow;} The HTML: This line has a span assigned a class which gives <span class="hilights">these words </span> a yellow background. background-color:blue; background-image: url{clouds.jpg} Background-repeat: repeat Values: repeat - tiles the image both horizontally and vertically (default) repeat-x – tiles the image horizontally repeat-y – tiles the image vertically no-repeat – does not tile at all background-attachment: fixed Values: fixed – prevents the background image from scrolling scroll – allows the image to scroll with the contents of the page background-position: left top Values: percentage or absolute distance x: left, center, right y: top, center, bottom Combined background: yellow url(europe5.jpg) center top repeat-y fixed; 19 Introduction to Cascading Style Sheets Hover Used for Background Color a:hover {background-color:#ff3300} Consider the following style: #menu a { color:white; text-decoration:none; background-color:blue; font-size:16px; padding:0.2em 0.6em; border-right:1px solid white; } #menu a:hover { background-color:#ff3300; } With the above styles, the background (of a td in this case) changes color when hovered over. 20 Introduction to Cascading Style Sheets Position A more powerful way than tables for laying out pages. Three kinds of CSS Positioning: 1. Relative - relative to (offset from) the element’s position in the “natural flow” of the page. (Any element has a “natural” position based on where it is in the code.) 2. Absolute - exact position relative to the body or to the nearest ancestor that has been positioned. 3. Fixed – The element is fixed with regard to the browser window. This makes an element (such as a background image) “fixed” in the browser window, i.e., it stays in place as the rest of the page content is scrolled. Relative Positioning p {position:relative; top: -10px;} The above would move paragraphs up 10 pixels from where they would normally start. Values; After the “position: relative;” you can specify top, bottom, right, left, with a distance value for each. Distances can be in pixels, em’s, percentages, etc. Absolute Positioning #menu {position: absolute; top: 10px; left: 15px;} Values; After the “position: relative;” you can specify top, bottom, right, left, with a distance value for each. Distances can be in pixels, em’s etc. 21 Introduction to Cascading Style Sheets With positioning, you can even have elements overlap: HTML for the above: <div id="photo1"> <img src="strasbourg1.jpg" alt="Strasbourg" /> </div> <div id="photo2"> <img src="strasbourg2.jpg" alt="Strasbourg" /> </div> CSS for the above: #photo1 #photo2 {position: absolute; top: 20px; left: 15px;} {position: absolute; top: 200px; left: 275px;} You can determine which is on top by using the z-index property: #photo1 {position: absolute; top: 20px; left: 15px; z-index: 0;} #photo2 {position: absolute; top: 200px; left: 275px; z-index: 1;} The higher the z number, the higher it is in the stack. Fixed Positioning Using the fixed positioning, you can have a stationary menu without having to resort to frames. #mainmenu {position: fixed; left: 15px;} 22 Introduction to Cascading Style Sheets Dynamic Effects Effects CSS provides opportunities for a variety of dynamic effects, including: Rollovers Pop-ups Drop-down menus One Example: The following CSS formats the menu (in the HTML, just a series of links) and causes a rollover effect for menu items #menumain {position: fixed; left: 15px;} a { display: block; padding: 4px; text-decoration: none; width: 5em; margin: 2px; color: #8D4F10; font-family: Arial;} a:link, a:visited { background: #FFCC66; border: 2px outset #AAA670; color: black; } a:focus, a:hover { background: #FF6633; border: 2px outset #DAA670; color: black; font-size: 100%;} a:active { background: #BB8E60; border: 2px outset #BB8E60; } 23 Introduction to Cascading Style Sheets Another Example: When the cursor is held over one of the links in the text, a pop-up window appears: For this and many more copiable examples of dynamic effects with CSS, see Dynamic Drive CSS Library: www.dynamicdrive.com/style Comments Comments can be inserted in style sheets by the use of a preceeding /* and */ at the end: For example: /* This is a comment 24 */ Introduction to Cascading Style Sheets Resources Websites: W3Schools CSS Tutorial - w3schools.com/css/ EchoEcho.com CSS Tutorial - www.echoecho.com/css.htm Dynamic Drive CSS Library - www.dynamicdrive.com/style Highly Recommended Book: Castro, Elizabeth. HTML, XHTML & CSS 6th ed. Peachpit Press. Berkeley, CA. 2007. 25 Introduction to Cascading Style Sheets Index hover · 18, 20 HTML · 5 A I absolute positioning · 21 attributes · 4 id · 7 inherit (property) · 15 inheritance · 10 in-line styles · 4 internal style sheets · 4 B backgrounds · 19 blink · 15 border-color · 17 borders · 3, 17 border-style · 17 border-width · 17 J justify · 15 C L center · 15 classes · 5, 7 Colors · 12 Comments · 24 Context · 7 left · 15 line height · 15 line-through · 15 link (to style sheet)· 9 links · 18 location · 11 D M declarations · 6 decoration · 15 divisions · 5 drop-down menus · 23 Dynamic Drive CSS Library - www.dynamicdrive.com/style · 25 dynamic effects · 23 margins · 16 menus · 23 N Notepad · 8 E EchoEcho.com CSS Tutorial · 25 editorial styles · 2 external style sheets · 4 O overline · 15 F P fixed positioning · 22 font-family · 14 fonts · 14 font-size · 14 font-style · 14 font-weight · 14 format · 6 padding · 16 pixels · 15 pop-ups · 23 position · 21 precedence · 10 properties · 6 pseudo-Classes · 7 H R hexadecimal · 12 relative positioning · 21 26 Introduction to Cascading Style Sheets resources · 25 RGB · 12 right · 15 rollovers · 23 U S V selectors · 6, 7 spacing · 6 spans · 5 specificity · 10 style elements · 4 style rules · 6 style sheets · 4, 8 values · 6 viewing other people’s style sheets · 9 underline · 15 W W3C · 2 W3Schools CSS Tutorial · 25 workshop objectives · 1 World Wide Web Consortium · 2 T text · 14-15 text-align · 15 text-decoration · 15 text-indent · 15 X XHTML · 2, 5 27