~~SLIDESHOW~~ ====== Introduction to Cacscading Stylesheets (CSS) ====== **Contact Hour 15**: To be discussed on Monday 20th March, 2012. **Lecturer**: [[C.P.Jobling@Swansea.ac.uk|Dr Chris P. Jobling]]. ---- The contents of these notes and all the examples are from Chapters 7--9 of Castro and Hyslop, //HTML5 and CSS3: Visual Quickstart Guide//, 7th Ed., PeachPit Press, 2012. These notes are incomplete and you are invited to contribute to them by getting an account on this wiki. ===== Introduction to CSS ====== * [[#CSS Building Blocks]] * [[#Working With Stylesheets]] * [[#Defining Selectors]] ===== CSS Building Blocks ===== * [[#What is a Style Sheet?]] * [[#Constructing a Style Rule]] * [[#Adding Comments to a Style Rule]] * [[#The Cascade: When Rules Collide]] * [[#A Property's Value]] * [[#CSS Colours]] ===== What is a Style Sheet? (1) ===== A style sheet is a text file that contains one or more rules that determine -- through properties and values -- how certain elements in a web page should be displayed. ===== What is a Style Sheet? (2) ===== There are CSS properties for controlling such basic formatting as: * font size and colour * layout properties such as positioning and float * print controls for deciding where page breaks should appear ===== What is a Style Sheet? (3) ===== There are also several dynamic properties such as visibility which are useful for creating drop-down menus and other interactive components. ===== What is a Style Sheet? (4) ===== * Various versions of CSS, but CSS 2 has widest support and CSS 3 is becoming widely supported in the current generation of browsers * CSS works best when using HTML in a standards-driven design approach. ===== Constructing a Style Rule ===== * Single property: h1 { color: red; } * Multiple properties: h1 { color: red; background: yellow; } See also [[#Defining Selectors]] ---- * //Selector// -- name of an element, here ''h1'' * //Declaration// -- ends in semicolon h1 { declaration; } * //Property// -- e.g. ''color'' * //Value// -- separated from property by a colon: color: red; Adding Comments to a Style Rule The Cascade: When Rules Collide A Property's Value CSS Colours ===== Adding Comments to a Style Rule ===== * It is a good idea to add comments to your style sheets so that you can remember what particularly complicated style rules are supposed to do. * CSS uses C-style block comments /* images will have a solid red 4 pixel border */ img { border: 4px solid red} ---- * Multiline comments are allowed * You can put comments around a style rule to hide it temporarily from a browser. Good for debugging! * Comments cannot be nested: ''/* /* this is illegal */ */'' * End of line comments are also possible as in: img { border: 4px solid red} /* images will have a solid red 4 pixel border */ ===== The Cascade: When Rules Collide ===== * Which style is applied if there are several styles all addressing same element? * CSS engine uses: //inheritance//, //specificity// and //location//. * [[#The Cascade: Inheritance]] * [[#The Cascade: Specificity]] * [[#The Cascade: Location]] ===== The Cascade: Inheritance ===== * **Inheritance**: a CSS property affects the element defined by the selector and is inherited by its descendants: ===== Example 1 ===== If p { color: red; } is used with

I'm some emphasized text inside a red paragraph. What colour am I?

Choices: 1 black; 2: red; 3: don't know. ===== Answer ===== 2. I'm red. The ''em'' element is a descendant of the red ''p'' so it will also be red. If you want a yellow emphasis inside red paragraphs use: p em { background-color: yellow; } ===== The Cascade: Specificity ===== * **Specificity**: if there is more than one style that can be applied to a given element, the style which is the most specific wins. ===== Example 2 ===== If: p { color: red } p.group { color: blue } p#one { color: green } p#one { color: magenta } What colour will each of the following paragraphs be? (choices 1: red; 2: blue; 3: green; 4: magenta)

1. I'm a generic paragraph. What colour am I?

2. I'm a group-class p paragraph. What colour am I?

3. I'm a group-class p element with and id of one. What colour am I?

===== Answers =====

1. I'm a generic paragraph. I'm red! (1)

2. I'm a group-class p paragraph. I will be blue (2)

3. I'm a group-class p element with and id of one. There are four rules that could apply. The first two are overruled by the more specific last two. The position breaks the tie between these two: the one that appears later wins, and thus I am magenta! (4)

Don't believe me? [[http://www.bruceontheloose.com/htmlcss/examples/chapter-07/specificity.html|Try it yourself]]! ===== The Cascade: Location ===== * Which style is applied if there are several styles all addressing same element? * Appearance of the style in the "//Cascade//" determines which style wins. * Rule is **most locally applied style** wins: * styles in external style sheets are //overridden by// * styles defined in head of document are //overridden by// * styles defined in internal style sheets are //overridden by// * styles defined in an element are //overridden by// * styles defined in user's own browser! ===== The Cascade: Location ===== Any styles that are defined up to the point of an ''@import'' are overridden by the styles defined in the imported style sheet. ===== A Property's Value: Inherited ===== Use the ''inherit'' value when you want to explicitly state that a property will be the same as the element's parent. ===== A Property's Value: Predefined values ===== Most CSS properties have a few predefined values that can be used. * Example: the ''display'' property can have values ''block'', ''inline'', ''list-item'', or ''none''. * Unlike HTML, such values do not need to be enclosed in quotes; in fact it is illegal to do so! ===== A Property's Value: Bare numbers ===== Very few CSS properties accept numbers without unit, e.g. 3. * The most commonly used ones are ''line-height'' and ''z-index''. * Others are mostly for print and aural style sheets. ===== A Property's Value: URLs ===== URLs are used for properties that allow you to set the location of another file (e.g. another stylesheet, or a background image). * Example ''url(file.ext)''. * URLs are relative to the style sheet and not the HTML document that loads the style sheet! ===== Lengths and percentages ===== * Many CSS properties take a length for their value. * All length values must contain a quantity and a unit, with no spaces between them * for example ''3em'' or ''10px'' * an exception is ''0'' which can be written without units. ===== Lengths and percentages: Relative to font size ===== E.g. ''2em'' meaning twice the size of the parent; ''3ex'' meaning three times the height of an x character. ===== Lengths and percentages: Relative to resolution ===== E.g. ''16px'' is the size of 16 pixels on the current resolution (most monitors display between 72 and 96 pixels per inch). ===== Lengths and percentages: Absolute units ===== These are self explanatory: inches (''in''), centimeters (''cm''), millimeters (''mm''), points (''pt''), and picas (''pc'') * These should only be used when the size of the medium is known, e.g. when printing. ===== Lengths and percentages: Percentages ===== E.g. ''65%'' are relative to some other value. For a font-size ''50%'' is same as ''0.5em''. ===== Lengths and percentages: Recommendations ===== In general, to cope with the variation of monitor resolution, etc, ''em'' and ''ex''' or percentage units should be used in preference to pixel or absolute units. The only exception is stylesheets for print where in general the size of the medium is known (e.g. A4 is 8.27in x 11.69in) -- but you are not likely to be dealing with print very often. ===== CSS Colors =====
Aqua
#00FFFF
Black
#000000
Blue
#0000FF
Fuchsia
FF00FF
Gray
#808080
Green
#008000
Lime
#00FF00
Maroon
800000
Navy
#000080
Olive
#808000
Purple
#8000080
Red
FF0000
Silver
#C0C0C0
Teal
#008080
White
#FFFFFF
Yellow
FFFF00
* Note that the colour names and hexadecimal values are not case sensitive, not even in HTML. ---- * There are several ways to specify colours for CSS properties. * First, and easiest, the value can be one of 16 predefined color names, but this limited range can get boring pretty quickly. * Here are the 16 predefined color names together with their hexdecimal codes. ===== Defining Colours with RGB Values =====
To Get this Colour
Use * Hexadecimal values (00-FF): ''background-color: #7fffff'' * Decimal values (0-255): ''background-color: rgb(127,255,255)'' * Percentages: ''background-color: rgb(50%,100%,100%)'' See also the web safe colour palette (colours which look reasonable on most monitors) [[http://www.cookwood.com/html/colors/websafecolors.html|www.cookwood.com/html/colors/websafecolors.html]]. ===== Additional Colour Controls in CSS3 ====== CSS3 introduces two additional ways to define colours: /* Hue-Saturation-Lumonosity */ p color: hsl(H,S%,L%); /* alpha (transparency */ p.a color rgba(r%, b%, g%, a%); p.b color hsla(H,S%,L%,A%); See Castro and Hyslop for examples. ---- For HSL, H is a number from 0 to 360 representing points on colour wheel that starts at red at 0/360 and goes through yellow at 60, green at 120, cyan at 180, blue at 240 and magenta at 300. S is the saturation as a percentage with low numbers moving towards grey, and for luminosity large percentages move towards white. Alpha is transparency with low numbers being more see-through than high numbers. ===== Colour Wheels and Colour Pickers ===== Bandon Mathis' HSL Color Picker: [[http://hslpicker.com/|hslpicker.com]] > Pick a Hue from 0 to 360 and with saturation at 100 and luminosity at 50 and > you'll have the purest form of that color. > Reduce the saturation and you move towards gray. Increasing the luminosity > moves you towards white, decreasing it moves you towards black. See also [[http://www.workwithcolor.com/hsl-color-picker-01.htm|www.workwithcolor.com/hsl-color-picker-01]] ===== Working With Stylesheets ===== * [[#An External Style Sheet]] * [[#An Internal Style sheet]] * [[#Media-Specific Style Sheets]] * [[#Offering Alternate Style Sheets]] * [[#Learning from your Peers]] ===== An External Style Sheet ===== * Just a text file with .css extension. * Contents are style declarations. ===== Linking an external style sheet ===== La Casa Milà ===== An Internal Style sheet ===== Style commands put in header La Casa Milà ===== Order is Important ===== * Local styles will always override any styles that are imported before the style tag. For [[http://www.bruceontheloose.com/htmlcss/examples/chapter-08/importance-of-location.html|example]]: ===== Aside: Importing External Style Sheets ===== * Import definitions from another style sheet (not recommended by Castro and Hyslop) La Casa Milà ----- * You can also use ''@import'' inside an external style sheet, e.g. to load common settings prior to customization. * As it is ignored by older generation browsers, you can use ''@import'' to effectivley hide the advanced properties from browsers that don't support them. Relative URLs in style sheets are interpreted relative to the style sheet, not the HTML document. ===== Aside: Applying Styles Locally (never do this!) ===== * You can apply a style setting to a single element by using the style attribute.
Now is the winter of our discontent
made glorious summer by this Son of York!
Produces:
Now is the winter of our discontent
made glorious summer by this Son of York!
---- There is an exception to every rule and local style definitions should only be used for one-off changes or exceptions. Overuse (e.g. as in Word or Frontpage) makes HTML code hard to read and harder to maintain. ===== Media-Specific Style Sheets ===== * You can designate a style sheet to be used only for a particular output. * Uses ''media="//output//"'' in link or ''@media //output// { ... }'' to group styles in styesheet. * Default is ''media="all"'' * Examples: [[http://www.bruceontheloose.com/htmlcss/examples/chapter-08/media-specific-style-sheets.html|in link]]; [[http://www.bruceontheloose.com/htmlcss/examples/chapter-08/base-with-media-print.css|base.css with media print]] ---- List of media types: * ''all'' -- the default * ''aural'' -- speech only * ''braille'' -- for blind users, touch devices * ''handheld'' -- for mobile devices, e.g. tables, phones, iPod touches, etc. * ''print'' * ''projection'' -- e.g. slideshows for lectures * ''tty'' -- "teletype" terminals, that is without graphics * ''tv'' -- for smart TVs and set-top boxes ===== Alternate Style Sheets ===== * Offering your users alternative stylesheets. [[http://www.bruceontheloose.com/htmlcss/examples/chapter-08/alternate-style-sheet.html|View example in your browser]]((Not Safari or Chrome!)) then choose //View Page Style// (or equivalent) La Casa Milà ---- *Link without ''title'' attribute is always applied *First link with ''title'' is the default *Second or subsequent links with titles are available as choices ===== Learning from your Peers ===== Open the page. View source. Follow link to stylesheet. Demo: [[http://www.swan.ac.uk|www.swan.ac.uk]] ===== Defining Selectors ===== * [[#Constructing a style rule]] * [[#Constructing selectors]] * [[#A Catalogue of style selectors]] ===== Constructing selectors ===== * A selector can define up to five different criteria for choosing the elements that should be formatted: * The //type// or //name// of an element * The //context// in which the element is found * The //class// or //id// of an element * The //pseudo-class// of an element or the //pseudo-element// itself * Whether an element has certain //attributes// and //values//. * A selector can include any combination of these criteria. * In addition you can apply the same declaration to a group of selectors. ===== Another Example ===== To illustrate the various style selectors, and how the work, we apply the simple style declaration ''color: red'', to various selections of an [[/eg-146/selectors/nostyle.html|example]] document. Follow the links to [[http://www.bruceontheloose.com/htmlcss/examples/#chapter-9|Chapter 9: Defining Selectors]] to see these examples live. ---- Antoni Gaudí – Introduction

Antoni Gaudí

Many tourists are drawn to Barcelona to see Antoni Gaudí's incredible architecture.

Barcelona celebrated the 150th anniversary of Gaudí's birth in 2002.

La Casa Milà

Gaudí's work was essentially useful. La Casa Milà is an apartment building and real people live there.

La Sagrada Família

The complicatedly named and curiously unfinished Expiatory Temple of the Sacred Family is the most visited building in Barcelona.

It is important to note that only the style declaration is changing! ===== A Catalogue of style selectors ===== I will demonstrate these in the lecture. ---- My cheat-sheet: - Select by name: name.css - Select by class: class.css - Select by id: classid.css - Select by context: context.css - Selecting elements by parent: child.css - Selecting the first child element: firstchild.css - Selecting the first child element: firstchild2.css - Selecting sibling elements: adjsibling.css - Pseudo-elements: first line of an element: firstline.css - Pseudo-elements: first letter of an element: firstletter.css - Pseudo-elements: selecting elements based on state: state.css - Selecting Elements based on Attributes: attribute.css - Selecting groups of elements: group.css - Combining selectors: combine.css ===== Selecting elements by name ===== * This selector will choose all of the h2 elements in the document ([[/eg-146/selectors/name.html|result]]) h2 { color: #f00; } ===== Selecting elements by class ===== * This selector will choose all of the elements which have a class attribute equal to "''project''" ([[/eg-146/selectors/class.html|result]]): .about { color: red; } ===== Selecting elements by id ===== * This selector will choose the element with an ''id'' equal to ''"gaudi"'' ([[/eg-146/selectors/classid.html|result]]): #gaudi { color: red; } ===== Selecting Elements by Context ===== * This selector selects all paragraphs that are children of the ''article'' with class ''"about"'' ([[/eg-146/selectors/context.html|result]]) article.about p { color: red; } ---- Other ways to get the same effect Any ''p'' that is a descendant of any ''article''. The least specific approach. article p { color: red; } Any ''p'' that is a descendant of any element with the ''about'' class. The second most specific of the three. .about p { color: red; } All three selectors above provide the same effect, so only one of them is required to make the text red. The second selector -- ''article p {}'' -- is preferred because it's the least specific. Generally speaking, [Castro and Hyslop] recommend making your selectors only as specific as necessary to yield the desired effect. That way, it's easier to override a selector with a more specific one for times when you want the style to deviate. ===== Selecting elements by parent ===== * This descendent selector will only choose those ''p'' elements that are children((Not grandchildren, great-grand children, and so on.)) of the ''article'' element of the ''about'' class. In order to qualify, they may not be contained within any other element ([[/eg-146/selectors/child.html|result]]): article.about > p { color: red; } ---- Only the first two ''p'' elements are children of the ''artcle'' element with the ''about'' class. The other two ''p'' elements are children of the ''section'' elements within the ''article''. ===== Selecting the first child element ===== * This selector chooses only the ''p'' element that is the //first child// of the ''article'' element with the ''about'' class ([[/eg-146/selectors/firstchild.html|result]]): article.about p:first-child { color: red; } '':first-child'' is a //pseudo-class//. In this case, nothing happens, because ''h1'' not ''p'' is the //first child// element of the ''article'' with class ''about''! ===== Selecting the first child element (2) ===== * This works ([[/eg-146/selectors/firstchild2.html|result]]): article.about h1:first-child { color: red; } ---- ''h1'' is the first child so this works ===== Selecting sibling elements ===== * This selector chooses only those ''p'' elements which directly follow a sibling ''p'' element within an ''article'' with an ''about'' class ([[/eg-146/selectors/adjsibling.html|result]]): article.about p+p { color: red; } ===== Pseudo-elements: first line of an element ===== * This selector will choose the first line of each ''p'' element ([[/eg-146/selectors/firstline.html|result]]): p:first-line { color: red; } ===== Pseudo-elements: first letter of an element ===== * This selector will choose the first letter of each ''p'' element ([[/eg-146/selectors/firstletter.html|result]]): p:first-letter { color:red; } ===== Pseudo-elements: based on state ===== * You can't specify in code what state a link (''a'' element) will have, it is controlled by your visitors. You can however give visual feedback based on the state by use of the following pseudo-elements ([[/eg-146/selectors/state.html|result]]): a:link { color: red; } a:visited { color: orange; } a:focus { color: purple; } a:hover { color: green; } a:active { color: blue; } ---- Explanation: the link is shown in red. As the mouse moves over the link (//hover//) it changes to green. If link has focus (use tab key to achieve this) it turns purple. While you press the link (before you release) it is blue. When the link has been visited it turns orange. ===== Selecting elements based on attributes ===== * This selector will choose the ''section'' elements which have a class attribute ([[/eg-146/selectors/attributes.html|result]]): section[class] { color: red; } ---- You can also select based on value:active * ''//attribute//="value"'' -- selects attributes whose value is equal to ''//value//'' * ''//attribute//~="value"'' -- selects attributes whose value //contains// ''//value//'' * ''//attribute//|="value"'' -- selects attributes whose value //equals// or //starts with// ''//value//'' * ''//attribute//^="value"'' -- selects attributes whose value //begins with// ''//value//'' (new in CSS3) * ''//attribute//$="value"'' -- selects attributes whose value //ends with// ''//value//'' (new in CSS3) * ''//attribute//*="value"'' -- selects attributes whose value //contains at least one// match of ''//value//'' (new in CSS3) See Tips on Pages 234--235 of Castro and Hyslop for examples of how to ue these ===== Groups of elements ===== You can select any number of individual selectors, as long as you separate each with a comma ([[/eg-146/selectors/context.html|result]]): h1, h2 { color:red; } ---- The selectors do not need to be on a line of their own, but many developers use this convention as it makes the style definition (and what elements it applies to) easier to read at a glance. Particularly when there are a lot! ===== Combining selectors ===== * You can also combine selectors each you need to be particularly precise ([[/eg-146/selectors/combine.html|result]]): .project h2[lang|="es"] + p em { color: red; } ---- **Explanation** "Chose only the ''e,'' elements that are found in the ''p'' elements that are immediately adjacent to ''h2'' elements that have a ''lang'' attribute whose value begins with ''es'' inside any element with a ''class'' equal to ''project''. The example above is an extreme one to demonstrate what's possible. Following are a few ways you could achieve the same results, moving from least specific to most specific: em { color: red; } .project em { color: red; } .about .project em { color: red; } #gaudi em { color: red; } ===== Summary ====== * [[#CSS Building Blocks]] * [[#Working With Stylesheets]] * [[#Defining Selectors]] ===== Next ===== * Formatting Text with Styles * Layout with Styles