CSS

From MobileRead
Jump to: navigation, search

CSS stands for Cascading Style Sheet where a style sheet controls the presentation of information in a document. For tips using CSS in an ePub see CSS HowTo. The new strategy for CSS changes is to create CSS3 modules and merge them into CSS level 2.1

Contents

[edit] Overview

A Cascading Style Sheets, level 2 (CSS2) is a style sheet language that allows authors and users to attach style (e.g., fonts, spacing, and aural cues) to structured documents (e.g., HTML documents and XML applications documents for example: ePub). By separating the presentation style of documents from the content of documents, CSS2 simplifies Web authoring and site maintenance. Styles can be in a separate file or in the source document or a mix of the two.

A style sheet in a separate file must be referenced from the document before it can be used. This is done in the head section with something like:

<link href="../Styles/stylesheet.css" rel="stylesheet" type="text/css" />

A simple style sheet might look like:

 h1 { color: blue;
     font-weight: bold;
     font-size: 12pt }
 h1, h2, h3 {text-indent: 0em}
 body {font-size: small; widows:2; orphans:2; 
      margin-left: 5px; margin-right: 3px }

Style information may be contained in one or more files (usually with a .css extension), within a <style> </style> block in the header element (as shown below),

 <style type="text/css">
    h1 { color: blue }
 </style>

or as a style attribute in a tag such as:

 <h1 style="color: blue">

The entries in CSS are called properties. The is a full list of properties for CSS.

[edit] Cascade

Since it is possible that the same style could be defined differently in different places the cascade rule will be applied. The more specific definition will override the more generic definition. Note in the example above the <body> tag specifies a font-size that will be overridden by the more specific <h1> tag. (h1 is within the body so it is more specific.)

A rule may also be in more than one place. The more specific case is chosen. However a ruleset in a less specific entry may still be used if the specific rule is not specified in the more specific instance. For example a style entry in the header of a file is more specific than one in a separate CSS file, but if the style entry in the header does not specify the color and the same entry in the CSS file does then the specified color would still be used.

It is also possible to have several links to different files. In this case the last link takes precedence over earlier links.

[edit] Syntax

A style entry generally begins with a ruleset which a keyword (a tag name or the value of the class attribute used as a selector) with optional modifier and the data between {}. Another type of entry is the ATRule which begins with @keyword and ends with a semicolon (;)

If the ruleset is an attribute it starts with a point (.) and can be used with a tag name to provide more control for example: h1.title. An entry using an attribute might appear as .sample to apply that attribute entry to all tags.

The data entries between the {} are all specified with a token name followed by a : and a value. The value may have units and is ended with a ; (a ; is optional for the last entry). White space may be used as desired except that units, when used, must be connected directly after the number.

[edit] Units of Measurement

Non-zero coordinate and size values will have specified units. These values need not be integers. Note that some are scalable, based on the current font size or other existing values, while some are fixed.

px Pixels
ex x-height of current font
em font-size of current font
pt Points = 1/72 in
in Inches
cm Centimeters
mm Millimeters
pc Picas = 12 pts
% percentage

Absolute length units are fixed in relation to each other. They are mainly useful when the output environment is known. The absolute units consist of the physical units (in, cm, mm, pt, pc) and the px unit:

   in: inches — 1in is equal to 2.54cm.
   cm: centimeters
   mm: millimeters
   pt: points — the points used by CSS are equal to 1/72nd of 1 in.
   pc: picas — 1pc is equal to 12pt.
   px: pixel units — 1px is equal to 0.75pt.

[edit] The CSS pixel

For CSS, the absolute dimensions are either anchored (i) by relating the physical units to their physical measurements, or (ii) by relating the pixel unit to the reference pixel. For print media and similar high-resolution devices, the anchor unit should be one of the standard physical units (inches, centimeters, etc).

For lower-resolution devices, and devices with unusual viewing distances, the W3C is recommended instead that the anchor unit be the pixel unit. For such devices it is recommended that the pixel unit refer to the whole number of device pixels that best approximates the reference pixel. The reference pixel is the visual angle of one pixel on a device with a pixel density of 96dpi and a distance from the reader of an arm's length (i.e. 0.26 mm). Thus a device using pixel units as a reference will not necessarily have physical units that are accurate. For a retina display there will not be a 1:1 correspondence. The W3C is trying to make the image size consistent on all displayed devices. This goal can lead to display problems when images are resized.

Boxsize.gif

[edit] Boxes

Each object in CSS is defined by a box (sometimes referred to as a block). This includes images, paragraphs of text, sections, and even the body statement in HTML. There is an artificial block called a page (@page) which refers to the screen area on an eBook Reader which can only have page related things like margins and sizes. Each object can have a transparent margin around it. In addition they can have a Border (which can include a line), and padding as shown in the image on the right. Objects can be inside other objects so a paragraph object can be inside a page object. The definitions will accumulate so that a paragraph left margin, for example, is in addition to a page left margin. However vertical margins in a normal flow are collapsed meaning only the larger of the two margins is used. If any item is not defined it is assumed to be zero (0).

The properties include:

  • Margin properties: 'margin-top', 'margin-right', 'margin-bottom', 'margin-left', and 'margin'
  • Padding properties: 'padding-top', 'padding-right', 'padding-bottom', 'padding-left', and 'padding'

Shorthand properties allow entering all the values without having to specify each one by name separately. This is done by assuming a specific order to the properties. The values are listed as: top, right, bottom, left. If only one entry is provided it is applied to all the 4 values. If only two entries are provided then the first is the top and bottom while the second is the right and left. Values for margins can be negative but not padding.

Values are calculated with reference to a width property, which if not specified defaults to the page width or the previous width. There are 'margin-width' and 'padding-width' properties which can be specified with length units or as a percentage. Auto is also allowed which is the same as not specifying a width.

[edit] Borders

Borders are different from Margins and Padding in that they are designed to be seen. Thus a border width is specified as thin, medium, thick which causes a visible line to be drawn around the object. This line can have a style as well such as solid, dotted, etc.

  • Border properties: Border width: 'border-top-width', 'border-right-width', 'border-bottom-width', 'border-left-width', and 'border-width'
  • Border color: 'border-top-color', 'border-right-color', 'border-bottom-color', 'border-left-color', and 'border-color'
  • Border style: 'border-top-style', 'border-right-style', 'border-bottom-style', 'border-left-style', and 'border-style'
  • Border shorthand properties: 'border-top', 'border-bottom', 'border-right', 'border-left', and 'border'

Border Styles include any of the following:

  • none - No border. This value forces the computed value of 'border-width' to be '0'.
  • hidden - Same as 'none', except in terms of border conflict resolution for table elements.
  • dotted - The border is a series of dots.
  • dashed - The border is a series of short line segments.
  • solid - The border is a single line segment.
  • double - The border is two solid lines. The sum of the two lines and the space between them equals the value of 'border-width'.
  • groove - The border looks as though it were carved into the canvas.
  • ridge - The opposite of 'grove': the border looks as though it were coming out of the canvas.
  • inset - The border makes the entire box look as though it were embedded in the canvas.
  • outset - The opposite of 'inset': the border makes the entire box look as though it were coming out of the canvas.

Border colors are a color, transparent, or inherit (meaning get the color from the earlier or larger box) Colors can be specified as a number as in HTML or a standard name such as black, red, white. See color

Shortcuts for borders are in the order of width, style, and color (space separated)

Not all readers support shortcut properties or even padding and borders.

[edit] Connecting boxes

Of course a document consists of multiple boxes (blocks) in a flow. And these blocks are contained or are split among pages (@page). Here are some of the rules for how the blocks fit together.

Often there are more than one block on a page. If two blocks have top and bottom margins defined the rendering software will only use the larger of the two margins with the other being ignored. Of course if there is specific locations specified (such as float) then this collapsing will not occur. There is special treatment is one of the margins is a negative number which will adjust the margin downward.

Whether the box contents of a text block will be split is under control of widows and orphans settings. Some software (such as ADE) uses a default of two for these values but specified settings in the CSS will be honored. If you don't want a particular paragraph to be split in this way you can use the page-break-inside property set to avoid.

If is also possible to guide the pagination of paragraphs. For example you can force a page break to occur before or after a particular paragraph. Or, you might want a heading to not appear at the bottom of a page by itself. The properties page-break-before and page-break-after can be used to control this. Setting the value to 'always' will force a page break while setting the value to 'avoid' will allow you to connect two paragraphs (a heading and the first paragraph) together. If there is not room on the current page for the two items then they will be moved together to the start of a new page. Of course the widow/orphan control may still allow the paragraph to be split.

Pages can also be named which is useful if the page properties need to be changed. A CSS statement can use the page property to specify the named page to be used. See an example under tables below. Not all readers support @page, most notably iBooks.

[edit] Display

The display property is normally identified with the 'Block' value and can be used with images for example to allow them to use text centering. However providing a value of 'run-in' can allow a header to be placed inline with the following paragraph, thereby combining the two visually. Another useful value for display is 'none' which causes that item to not display at all. This could be used to retain the original page numbers of a book. A display set to 'hidden' does not display the data but the space it would have taken will still be shown. Another interesting entry is 'inline-block' which can be used in a CSS for a div statement to try and keep the whole entry within one page. For example a figure and its caption or more than one paragraph.

The ePub specification adds two values to the display choices. There are oeb-page-head and oeb-page-foot. They should not be displayed immediately or as a Block value. They are intended to be used for headers and footers. Once initiated they should appear at the top and bottom respectively of a visible page. The latest text content should be used. See headers and footers for more details.

[edit] Fonts

Fonts and Font sizes can be specified in the CSS. The font-size attribute can specify a specific size using units or a generic scalable size. The scalable sizes are to be preferred as then the user can override them as needed. These values include:

  • xx-small
  • x-small
  • small
  • medium
  • large
  • x-large
  • xx-large

A given system may not support all 7 sizes but may substitute the same size for missing values. Font-size can also be set to larger or smaller to request a one jump from the current size. Percentage values can also be used to change the font size.

See the article on Fonts for more information on fonts themselves and what CSS control there is over fonts. One trick to making a resizable font is to use 1em for the base size and scale the others from it, such as .6em or 1.2em.

It is also possible to specify the family of fonts. Unless you can guarantee the availability of a certain font family such as when it is embedded you should specify a list of choices where the last choice is as generic as possible.

font-family:"Courier New", Courier, monospace;

[edit] Text

In addition to fonts the CSS system provides control of the overall look, typography, of the text. Most text attribute effect blocks of text such as a paragraph but some control inline text. These attributes include

attribute value notes
text-indent number, %, inherit controls indent of first line in a block, may be negative.
text-align left, right, center, justify <string> inherit string value only used in a table to align text to a specific cell.
text-decoration none, underline, overline, line-through, blink, inherit blink is likely to be ignored.
color colors or number value 16 standard colors are recognized. see color.
text-shadow color and three numbers color is required. three number specify the shading distance, right, and down distance for the shadow. The values may be repeated after a comma for more effect.
letter-spacing normal, number added distance between letters, may be negative
word-spacing normal, number added distance between words, may be negative.
text-transform none, capitalize, uppercase, lowercase can be ignored for non-latin characters. Note that ADE does not support this.
white-space normal, pre, nowrap, inherit pre does not remove white space

Fonts themselves can also be changed. It is not a good idea to be overly specific on font attributes. For example specifying an exact font size is too restrictive. The user should be able to scale the font size up or down depending on their reading requirements. For example you can specify a new font size as a percentage of the default size or simply use the font size adjustment of larger or smaller.

font-size: smaller or font-size: 1em 

[edit] Leading

Leading is the distance between lines of text. Generally lines of text are vertically centered within a box boundary and evenly spaced however not all implementations support this. The line-height property can be used to specify a value for leading. One half the leading value will be used above and one half below the line. Values include:

  • normal - the default value determined by implementation to provide a pleasing effect.
  • <number> - an computed positive value by multiplying the font size
  • <length> - an explicit positive value with units specified.
  • <percentage> a positive value reference to the font size.
  • inherit - final computed value from an earlier box.

Note that if the line-height is less than the font height (size) the font will "bleed" outside the box.

[edit] color

The attribute value type "Color" refers to color definitions as specified in SRGB. A color value may either be a hexadecimal number (prefixed by a hash mark) or one of the following seventeen color names. The color names are case-insensitive.

Color names and sRGB values
Black.gif Black = "#000000" Green.gif Green = "#008000"
Silver.gif Silver = "#C0C0C0" Lime.gif Lime = "#00FF00"
Gray.gif Gray = "#808080" Olive.gif Olive = "#808000"
White.gif White = "#FFFFFF" Yellow.gif Yellow = "#FFFF00"
Maroon.gif Maroon = "#800000" Navy.gif Navy = "#000080"
Red.gif Red = "#FF0000" Blue.gif Blue = "#0000FF"
Purple.gif Purple = "#800080" Teal.gif Teal = "#008080"
Fuchsia.gif Fuchsia = "#FF00FF" Aqua.gif Aqua = "#00FFFF"
Orange.gif Orange = "#FFA500" a recent addition

Thus, the color values "#800080" and "Purple" both refer to the color purple.

[edit] Images

Properties for images can change where the image appears. To center an image on a page you must tell it that the image is a block. The following will work on most implementations except for ADE. For ADE the best workaround is to center a table with one column and one row and put the image inside the table.

 img.center {display: block; margin:auto;}

The float property allows paragraphs of text to flow around the image. The following example places an image against the left edge of the page. Legal values are none, left, right. Float will also work with blocks of text that are not in the main flow. (See column for another use of float.)

 IMG.icon { 
   float: left;
   margin-left: 0;
   margin-right: 3px;
 }

If you want one paragraph to appear to the right but the next paragraph to be under the image then your next paragraph should use the clear property

 P { clear: left }

Legal values include left, right, or both as related to previous floated blocks or images.

It is possible to specify the desired width and height of an image. By default these values are set to auto which will maintain the original aspect ratio of the image. Setting one value with the other set to auto will maintain the aspect ratio but setting both values may distort the image. For example setting both to 100% would distort the image on a device that does not have the same screen aspect ratio as the image. The image will be adjusted (scaled) to fit your specifications. Maintaining aspect ratio may cause blank areas (bars) to appear outside the image. More control can be found by embedding the image statement inside an SVG image.

Other useful settings are max-height, max-width, min-height and min-width. These will override the width and height properties.

[edit] Tables

Tables can be complicated objects to provide CSS for. For full information the CSS specification for tables should consulted. This section only provides basic information. Tables generally appear between text elements but it is possible to make them inline appearing on the left or right side similar to images.

There are several tags for tables. These include table, caption, th, tr, and td. In addition there are borders and spacing considerations for each of these elements. Note that CSS also works on wiki tables and are usually done by adding a style tag inline with the elements separated from the data with a single |.

To center a table you need only:

 table {
    margin-left: auto;
    margin-right: auto
 }

Borders around tables and between elements are generally invisible. The table attribute border="1" can cause the border to be seen. There are two basic borders, a double line and a single line. The style tag border-collapse can be used to define which you want. Values include: collapse, separate, and inherit

Sometimes a wider table would be better if it were rotated on the screen. This is not required in the ePub 2.0.1 specification, thus most readers do not support this feature but CSS defines a @page that can be used to define a rotated page. Hopefully this will be available in ePub 3.0. Here is what it might look like:

 @page rotated {size: landscape}
 TABLE {page: rotated; page-break-before: always}

Technically the page-break-before should not be necessary since any time the page name is changed there should be a page break.

[edit] Lists

Bulleted and numbered lists have special CSS properties. See these examples:

  • ul.dot {list-style-type:disc} - this is the default
  • ul.circle {list-style-type:circle}
  • ul.square {list-style-type:square}
  • ul.none {list-style-type:none} do not display any bullet.
  • ol.upper-roman {list-style-type:upper-roman}
  • ol.lower-alpha {list-style-type:lower-alpha}
  • ul.url {list-style-image:url('sqpurple.gif');} can also be used to specify your own.

An outline could be created using the following example: (note list-style can substitute for list-style-type)

ol {list-style-type: upper-roman;}
ol ol {list-style-type: upper-alpha;}
ol ol ol {list-style-type: lower-roman;}
ol ol ol ol {list-style-type: lower-alpha;}
ol ol ol ol ol {list-style-type: decimal;}

[edit] Testing CSS

[edit] For more information

Personal tools
Namespaces

Variants
Actions
Navigation
MobileRead Networks
Toolbox