Converting from HTML to CSS

Difference between HTML and CSS

  1. HTML: Specify content and structure (organization) of web pages
  2. CSS (Cascading Style Sheets): Specify appearance of web pages
    1. Old html provided simple defaults, like boldface and italics, but it was primitive from a graphic design perspective
    2. Page layout in html accomplished primarily via tables
    3. Style sheets allows a uniform presentation format to be used for an entire web-site (i.e., same style for many web pages)

HTML Tags to Add to Your Lexicon

  1. div: bundles up a discrete bunch of content, such as a sidebar, footer, or other content that needs to be specially formatted
  2. span: used for inline elements that require special formatting.
  3. dl, dt, and dd: useful for creating a glossary of terms (dl = definition list, dt = definition term, and dd = definition description)
  4. blockquote and q: block quotes for a snippet of text or for a single line of text

HTML to Forget

  1. font: Specify fonts in style sheets, rather than in html documents. If you look at old html documents created by visual tools, you'll see endless numbers of font tags that blow up the size of the page and make it take longer to load
  2. b and i: Use strong and em instead.
  3. table: Use CSS's page formatting commands instead
  4. html attributes that specify graphical information, such as bgcolor


Creating Styles and Style Sheets

Anatomy of a Style

  1. Style sheets consist of a list of styles
  2. Each style ctonains two parts, a selector that describes the html element being formatted and a declaration block that contains the formatting instructions for that element.
  3. A declaration block is a list of declarations, each of which is a formatting instruction.
  4. A declaration is a property-value pair followed by a semi-colon (;)
  5. Example:
      p { color: red; 
          font-size: 16px; 
        }
    

Associating Style Sheets with an HTML Document

  1. Internal Style Sheet: Specified with the html document. Internal style sheets are specified in a style element inside the head element at the beginning of the html document: <head> <style type="text/css"> p { ... } </style> </head>
    1. The type attribute tells the browser to interpret what follows as a css style sheet.
    2. internal style sheets are useful when developing a set of styles

  2. External Style Sheet: Specified in a separate file from the html document and linked to the html document using the link element
    1. Example <link rel="stylesheet" type="text/css" href="css/global.css" />
      1. rel indicates the type of link, in this case, a link to a style sheet
      2. type lets the browser know type of data to expect--a text file containing CSS
      3. href provides the URL address of the external CSS file

    2. external style sheets are used when maintaining a collection of web-pages that should be displayed using the same format.

  3. Inline: use the style attribute to apply a style specifically to a single tag element.
           <p style="font-size: 10px; color: red">
         

Selectors

  1. types of selectors
    1. tags
    2. classes (.): can be either global or associated with a specific tag
      1. global example: .break
      2. specific tag example: p.break
    3. ids (#): associated with a specific tag
      1. example: #banner
      2. uses of the id attribute
        1. to identify a single element, such as a banner, within a web page for formatting
        2. to identify a form element for javascript so that it can collect information from that element
        3. to identify any element within a web page whose content might be manipulated by javascript
        4. to identify specific sections within a web page so that internal links can be created for navigation
    4. descendent selectors (also called contextual selectors): use a list of selectors, such as "ol ol"
    5. *: universal selector-applies to every tag within its scope
      	* {...}: applies to every tag in the page
      	.announcement * { ... }: applies to every tag in content pinpointed
      	     by the .announcement class
            
    6. pseudo-classes and pseudo-elements
      1. pseudo-classes for links
        1. a:link: a regular, as-yet unselected link
        2. a:visited: a link that has been clicked at least once before
        3. a:hover: lets you change the look of a link as you roll over it with the mouse (useful when the link is an image in a navigation bar)
        4. a:active: what the link looks like in the instant that the user clicks on it (basically provides interim feedback during the act of clicking)
      2. pseudo-classes for paragraphs
        1. p:first-letter: specially formats the first letter of a paragraph (e.g., you might create a huge fancy letter in a different font)
        2. p:first-line: specially formats the first line of a paragraph (e.g., you might bold-face the first line or display it in a different color)
      3. :before/:after: allows you to place content, especially images, immediately before or after certain elements
        p.new:before { content: url(http://web.eecs.utk.edu/~bvz/new.jpg); }
        p.done:after { content: url(http://web.eecs.utk.edu/~bvz/checkmark.jpg); }
        <p class="new">Exam 1 scheduled for 6/20/10</p>
        <p class="done">Cover CSS selectors</p>
        
      4. child selectors: child selectors are supported by the CSS3.0 standard, so you can start experimenting with them
        1. :first-child: selects the first child for a tag (e.g., ul :first-child)
          1. it is important to put a space between the tag and the child selector
          2. ul:first-child, with no space, would mean select all ul tags that are the first child of some other tag.
        2. :last-child: selects the last child for a tag
        3. :nth-child(odd, even, an+b such as 3n+2): Especially nice for displaying columns of a table in different background colors or justifying text in a particular column
          1. 1,2,3, etc: applies to that column only. Numbering starts at 1, not 0
          2. odd: applies the style to odd-numbered children
          3. even: applies the style to even-numbered children
          4. an + b: applies the style to the bth child and every ath child thereafter. For example 3n+2 applies the style to the 2nd, 5th, 8th, etc. children
      5. type selectors: sometimes you want a style to apply to the first tag of a certain type within a content block, but you you cannot be sure whether or not it will be the first child. Type selectors let you specify that a style should be applied to the first occurrence of a tag within a certain content block. Like the child selectors, the type selectors are first-of-type, last-of-type, and nth-of-type. nth-of-type allows the same set of options as the nth child selector.

        As an example, suppose we want to color the text in the first paragraph of any div tag blue. We could try:

        div :first-child { color: blue }
        However, suppose that the first tag in the div block is a table. Then the text in the table will be colored blue, and the text in the first paragraph will be colored in the inherited color, which is probably black. We can avoid this problem by using the first-of-type selector:
        div p:first-of-type { color: blue; }
        Here are a couple more examples:
        #navigation_bar p:first-of-type { color: blue; }
        #navigation_bar td:nth-of-type(odd) { background-color: gray; }
        
  2. you can group selectors using comma separated lists
    h1, h2, h3, h4 { color: red; }
    
  3. class attributes can specify multiple classes <p class="pagebreak announcement">

Inheritance and the Cascade

  1. Inheritance is the process by which CSS properties applied to one tag are passed on to nested tags.
    1. If a property is not specified for a tag, then the browser will search for the first enclosing ancestor tag (i.e, the nearest ancestor tag) that defines the property.
    2. Example: Suppose you have the following style and content information:
      body { color: red }
      p    { color: blue }
      ...
      <body>
      <p>
         The <strong>wily fox</strong> eluded the hounds.
      
      The color for the content "wily fox" in the strong tag will be blue, since the p tag is the first nested ancestor to specify a value for color.
    3. some elements inherit (e.g., color) and some don't (e.g., borders). Examples of times when inheritance does not apply

      1. As a general rule, background colors, borders of elements, and properties that affect the placement of elements on the page or the margins are not inherited
      2. Web browser have their own internal style sheets, and they may have specific styles for tags, such as for header tags, that will override your inherited values. For example, if you provide a font-size for the body and the web browser provides a font-size for an h1 tag, then the web browser's font-size will prevail because its style is more specific.
      3. When styles conflict, the more specific style wins (as for example when the Web browser's style sheet specifies a more specific style for an h1 tag).
  2. Cascade is the process by which a virtual style-sheet is assembled for an element via inheritance, specificity, and location

    1. inheritance
    2. specificity

      1. one tag may have many applicable styles. As long as the styles do not conflict, they are all aggregated. For example:
        style rules
        p { font-size: 40px; }
        p.byline { font-style: italic; }
        p a { text-decoration: none; }
        
        content
        
        <p class="byline"> The <a href="vols">Vols</a> score 
        
        There is no conflict among the three styles, so they will all be applied to the a tag.

      2. when there is conflict, the more specific selector wins. The order from most-specific to least specific is (id, class, descendent selector, tag)
      3. In the above example, if the style rule for p is:
        p { font-style: plain;
            font-size: 40px; 
          }
        
        then p and p.byline have conflicting styles for font_style. p.byline wins because it is more specific.
    3. location: sometimes there is equal specificity because a style is specified in more than one stylesheet. In this case, the last style to be specified in physical order wins. inline always beats internal and external styles, because it is last. If the competition is between internal and external styles, then it is whichever comes last in the <head> block. Typically you specify external style sheets first, and then internal styles, because you typically want the internal styles to override the external styles.

      1. When you specify multiple classes, such as in the tag:
        <p class="pagebreak announcement">
        
        and there is a conflict in the style rules, the style associated with the class that is specified later in the sequence of style sheets, not the class attribute, will be used. In the above example, if the pagebreak class appears later in the style sheets then the announcement class, then the styles associated with the pagebreak class will be used in case of a conflict, despite the fact that the announcement class is listed later in the class attribute.

Value Types

The values that you specify for a property come in one of several forms:

  1. predefined values (e.g., rules="rows", "cols", "all", etc)
  2. lengths/percentages: make sure there is no space between the number and the length or percentage
    1. px: pixels-relative to resolution of monitor--100 pixels on a 600 pixel wide monitor will occupy 1/6 of the display, but on a 1200 pixel wide monitor will occupy 1/12 of the display. This is one drawback of using pixels.
    2. %
      1. The key idea you must remember when specifying percentages is that all browsers have a default font size, called the base font size.
      2. Percentages modify this base font size. They are also specified relative to a parent's size and changes are cumulative and multiplicative.
      3. Example: Suppose the base font size is 16pt and we have the rules:
        body { font: 75% }
        h1 { font: 200%}
        
        Then the font for body elements will be 75% of 16pt, or 12pt. The font for h1 elements will be 200% of the body's font, or 24pt. Note that the percentage change for the h1 element is multiplicative (16 * .75 * 2).

    3. em: This one is confusing because an em is used in typography as a unit of measurement which is equal to the size of a capital M in the current font. An em roughly denotes this meaning in some contexts in CSS, such as when specifying a text indent. For example, "text-indent: 5em" would cause the first line of a paragraph to be indented by 5 characters and "width: 60em" would cause a block element, such as a div, to be roughly 60 characters wide. However, when used in the context of font-size, an em is the same as %. For example "font-size: 2em" doubles the current font size.

    4. measurements appropriate only for fixed size output, such as a printed page

      1. in: inches
      2. cm: centimeters
      3. mm: millimeters
      4. pt: point size -- for monitors it is better to use % or em to modify the font size. In general, one point represents 1/72 of an inch on a printed page but it is much less consistent on monitors and you cannot trust the monitor to display it at this resolution. In general you should only use point size for printed documents.

  3. colors: a color for an element can be declared in a number of ways

    1. Predefined color names (16), such as navy, olive, or red
    2. RGB (red/green/blue) percentages: rgb(25%,0%,50%)
    3. RGB values between 0 and 255: rgb(64, 0, 128)
    4. RGB hexadecimals: #59007f
    5. Shortened RGB hexadecimals: #f34 is equivalent to #ff3344

CSS Properties

Style rules can be specified for a wide variety of visual attributes, including text, background, fonts, borders, margins, padding, lists, and tables. You must be careful when specifying property names, because they can differ from the comparable HTML attribute names or they can differ in the values that you specify. For example:

  1. in html you use bgcolor for table elements, but in a style sheet you use background-color
  2. in html you use align for the td element, but in a style sheet you use text-align
  3. in html you use border="1" but in a style sheet you must use both border-style: solid and border-width: 1 to get the same result. You cannot use border-width by itself.

Text

Common properties are:

  1. color
  2. text-align: specifies horizontal alignment. Valid choices are left, right, center, and justify. justify will try to make text line up on both margins.
  3. text-decoration: Valid choices are none, underline, overline, and line-through.
  4. text-indent: Usually you'll use ems to specify text indentation, since each em will be roughly one character. If you use % instead, then the amount of indentation will depend on the width of the tag block. For example, if you specify a text indent of 5% for a 600 pixel wide block, then the indent will be 30 pixels. A drawback of using percentages is that the indent will vary, depending on the block width.

Font

  1. font: sets all font properties at once--must specify properties in the order "font-style font-weight font-size font-family"

    1. there is a fifth property, font-variant, that may optionally occur between font-style and font-weight. However, it is not commonly used. If used it will convert lower case characters to small upper caps, with the small upper caps being smaller than an actual capitalized character.
    2. font-style and font-weight may be omitted, but font-size and font-family are required. You may optionally specify multiple values for font-family, in case the first value is not available.

  2. font-family
  3. font-size
  4. font-style: normal or italic
  5. font-weight: normal or bold

Box Model

All HTML elements can be considered as boxes. In CSS, the term "box model" is used when talking about design and layout.

The CSS box model is essentially a box that wraps around HTML elements, and it consists of: margins, borders, padding, and the actual content.

The box model allows us to place a border around elements and space elements in relation to other elements.

Explanation of the different parts:


Borders

  1. border: shorthand property for border-width, border-style, border-color -- border-style should always be provided while border-width and border-color are optional. Failure to provide a border-style will result in a default style of none being used, and hence no border will appear
  2. border-style: none, dotted, dashed, solid, etc.
  3. border-width: usually in px
  4. border-color

Margins

Usually use pixel values

  1. margin: shorthand property in order top, right, bottom, left (a useful mnemonic is clockwise from 12:00, which is the top of a clock)
  2. margin-top
  3. margin-bottom
  4. margin-left
  5. margin-right

Padding

Usually use pixel values

  1. padding: shorthand property in order top, right, bottom, left (a useful mnemonic is clockwise from 12:00, which is the top of a clock)
  2. padding-top
  3. padding-bottom
  4. padding-left
  5. padding-right
You can use padding to achieve hanging-indents:
    td, p, li {
      padding-left: 1em;
      text-indent: -1em
    }
Note that hanging indents must be specified for the individual items in a table or list, not for a table or a list.

Lists

  1. list-style-type: shape of the list item marker for unordered lists or the type of enumeration for ordered lists (e.g., upper-roman, lower-alpha)
  2. list-style-image:url('arrow.gif'): allows use to customize the image for an un-ordered list
  3. list-style-position: inside/outside--controls indenting, with "inside" value indenting further than outside

Tables

The style attributes for tables are different than their html counterparts so make sure that you use the right names.

  1. border-collapse: specifies whether or not table borders should be collapsed (collapse, separate)
  2. border-spacing: distance between the borders of adjacent cells
  3. empty-cells: whether or not to display borders and background on empty cells (show, hide)
  4. table-layout: sets layout algorithm used for a table (auto, fixed)