Chapter 3
CSS
Understand the importance of using CSS with XHTML
Learn CSS coding
Practice CSS
XHTML has been changed by the use of Cascading Style Sheets (CSS). As you may have noticed in Chapter 2, many of the attributes were grayed out. These attributes do work on EPUB devices, but it is strongly recommended that CSS be used.
Learning CSS is a very important task for working with EPUB files.
What Are Cascading Style Sheets (CSS)?
Let’s assume you are working with an EPUB file, specifically a novel. Throughout the novel, the paragraph tags (<p>) are used hundreds of times. When you look back later, you decide you want to change the margins, line indentations, etc. Even with using find and replace in Sigil, it would take time to change it all. Later, you decide to tweak it a little more. The process can become time consuming and may cause mistakes in the XHTML code. So, what to do?
The answer is CSS. CSS allows a change made in a single place to occur throughout the whole text layout. The beauty is that changes do not need to be made on every XHTML file to have a consistent layout.
In the previous chapter, we covered the <style> tag. The <style> tag allows the CSS entries to be placed in the XHTML file itself. An example of the <style> tag is shown:
Instead of having all of the styles within the XHTML files, all of the styles for the XHTML files can be centrally located. XHTML files can share styles, which can be changed in one place. So, every XHTML file that uses a CSS must have a link to it. The links look like this:
The name of the style sheet is Style0001.css and it is located in the Styles directory off the parent folder.
The content of the CSS has a specific format; however, you can change it a little bit. First, the selector is specified, followed by a curly bracket, then a declaration. The declaration is made up of a property, followed by a colon, then the value assigned to the property. A semicolon is next, followed by more declarations and semicolons, if needed. Finally, a closing curly bracket is needed to end the style. A sample layout is shown in Figure 3-1.
CAUTION
Be aware that the CSS rules may not perform the same on all reading systems!
Selectors
The selector specifies either the class name of the style and/or the tag to which the declaration rules apply. When specifying a class name, the attributes are used only on elements with the specified class. If a tag name is used, the attributes are used only on the specified tags. However, if both a class and tag name are specified, the attributes are used on the tags which also have the specified class name.
Class Name Assignment
CSS styles are given a name, and it is best practice to start the name with a letter, not a number. For example:
The example is self-explanatory. The name of the style is blue-text and it causes the associated element to have blue-colored text. In the next example, I’ll assign the style to a paragraph, so all the text in the paragraph will be blue:
Now, looking back at the style, or class name, you can see it starts with a period. The period is important. Since nothing comes before the period, the class name can be assigned to any tag. If you assign the style to the <html> or <body> tag, for example, all the text in the entire EPUB will be blue.
NOTE
Be careful when applying styles to the <html> or <body> tag since it will be applied to every element within the XHTML body. Try to place the styles on individual tags within the body.
Now, the second way to name a style is to make it only work with a specific tag. For example, to make text centered for a style named center-text to only work on paragraph tags, the style would be:
In this case, the style can only be applied to paragraphs. If you tried to assign it to a span tag, it would not work. For instance, the following element would work:
The following example would not work with the p.center-text style:
TIP
Unless you have styles with the same class name for different tags, you could simply place a period in front of all styles.
Tag Name Assignment
Another way to name a style is to name it with a tag name only. In the following example, a style is placed on all <h1> tags. The style will center the header and make it green.
From this example, you can see that multiple properties can be placed in one class name. The properties and values are separated by a semicolon, and it is best practice (although not necessary) to end the list with a semicolon before the closing curly bracket.
Just as you can add multiple properties to one style name or tag, multiple tags can be specified. For instance, if all headers were to be centered and blue, the class would be set up as shown:
NOTE
The list of rules or declarations can be on one line separated by semicolons, or they can be on multiple lines as long as they are still separated by semicolons.
It would be appropriate to also do the following:
Using multiple lines for the declarations makes it easier to read. The curly brackets can be placed as shown, with the first declaration, text-align:center;, on the top line as well. The closing curly bracket could be behind the second declaration. If you use Sigil, it automatically formats the sections as shown in the example.
Other possibilities exist for the selector, but we’ll cover those later in this chapter. Let’s get through the basics first.
Declarations
The declarations are made up of two parts. The first is the property, and the second is the value. Each property has specific values that can be assigned to it. Be aware that unlike XHTML attributes, the declaration values do not need to be in quotes.
There are nine property sections, as shown in Table 3-1. These sections can be split up in many different ways.
Table 3-1 Declaration Sections
Font Properties
The fonts make up the main part of the reading experience. Changing the appearance of the fonts can make a huge difference in a book. Table 3-2 shows the various properties for fonts.
Table 3-2 Font Properties
font-family Fonts are generically divided into typefaces. When specifying a family, you can name the typeface and allow the reading device to use a built-in font from the typeface style. The main typefaces are listed in Table 3-3 with an example font for each typeface.
Table 3-3 Typefaces and Sample Fonts
The list of typefaces can be quite extensive, but most reading devices only support a few.
NOTE
Download the EPUB tester.epub file from the McGraw-Hill website at
www.mhprofessional.com/EPUB, place the EPUB file in your reading device, and go to the page Font Family to determine which typefaces are supported.
Multiple typefaces can be specified, as well as multiple font family names. For example, if a CSS style named fontface was made to use the Times New Roman font family and then the Times font family and then any available Serif typeface, the line would be:
NOTE
Use quotes around any name that has spaces or is a CSS name or has an identical generic typeface name.
Keep in mind that reading systems on PCs will have a larger font base and can use various fonts. Mobile devices have only a few built-in fonts. If you use a specific font that most systems will not have, you need to embed the font. Font embedding is covered in Chapter 4.
font-size There are four ways to specify size for an EPUB: absolute, relative, percent, and length. It must be clear that on most reading systems, the reader has the ability to change the font size. For example, people with vision problems may enlarge the font quite a bit so that it is similar to a large-print book. When you specify a font size in the CSS, you need to be aware that you can affect the size the reader has set as the default.
What Are the Four Ways to Specify Size?
The first way to specify size is by absolute size. The options are xx-small, x-small, small, medium, large, x-large, or xx-large. The sizes are absolute from one to the next, where the next largest name produces a slightly larger font. Absolute sizes are not a specific size, but will vary depending on the reading system.
The values for relative size are either smaller or larger; again, these are not specific, but depend on the reading device.
The third option for font size is by percent. To specify a size of 100 percent is to have the text the same size as the standard text. To double the text size, use 200 percent. For half the size, use 50 percent. Similar to the relative sizes, percent is also relative to the current text size on the reading system. It is recommended to use percent whenever possible.
Finally, the last size is by length. The em is based on the width of the lowercase letter m for the typeface. For the current font 1 em should be its normal size. So, 2 em would be twice the size, 5 em would be five times the size, etc. All of this means that 1 em is the same as 100 percent, 2 em is the same as 200 percent, and so on.
A recommendation is to use either percent or em since the size is relative to the current typeface and size.
To specify that the header 1 (h1) style be two and half times the size of normal text using percent, the coding would be:
The code could also be specified by using em:
font-size-adjust If the first choice of font-family is not selected, then the second or third may be chosen. When this happens, you may need to change the aspect ratio of the second font to match the first. That way, the fonts will be similar in size. Even if an extra font is placed in with the “normal” font, they can appear the same size, or the size can be adjusted as needed.
Usually, font size is not too important, but some fonts have a completely different size compared to another. In these cases, it may be best to adjust the size so the new font is not too large or too small.
The best way to test this problem is to download the font adjuster.xhtml file from the McGraw-Hill website. With this file, you can specify the two fonts you want to use and then change the font-size-adjust property. Once you do this, view the file in Firefox (it must be Firefox since no other browser supports font-size-adjust).
How Do I Test font-size-adjust?
For the best way to test font-size-adjust, use Notepad++. Open the font adjuster.xhtml file in Notepad++. Make the necessary changes at the top of the file. Select Run from the menu and select Launch In Firefox. Once Firefox opens, see how similar the lines are to one another in length.
Switch back to Notepad++ and modify the font-size-adjust value appropriately (increase the value to make the second line longer; decrease the value to shorten the second line). Save the file in Notepad++ by pressing ctrl-s. Switch back to Firefox and press the f5 key to refresh the page to the new settings. Once the lines are similar in length, use the font-size-adjust value in your EPUB file.
Say you set the font to Impact instead of Arial but you want the fonts to appear as equal size. The Impact font is much smaller than Arial and must be adjusted by .68 so the two fonts appear to be similar in size.
NOTE
As with some XHTML tags and attributes, not all CSS properties work on every reading system. Be very aware of this fact as you use the CSS properties. Use the EPUB tester .epub file from the McGraw-Hill website to test a specific property with a reading device.
The code to change the font size to use Impact instead of Arial in a style called adjust would be:
font-stretch If a font contains a different face—that is, various sizes of each letter or glyph—the font-stretch property can use the other face. The font itself is not stretched or condensed. If no other face is included in the font, then nothing will happen.
For the font-stretch properties, there is both relative and absolute sizing. Relative sizing is based on the current font size, which is called normal. To make the font larger, there is wider; to make it smaller, there is narrower. Absolute sizing has no specific size definitions; there are only the following choices: ultra-expanded, extra-expanded, expanded, semi-expanded, semi-condensed, condensed, extra-condensed, and ultra-condensed. To make a style called stretch and make it condensed, the code would be:
It should be noted that no systems seem to currently support this property.
font-style There are three choices for font-style: normal, italic, and oblique. If a style has been changed and you wish to make it normal again, use normal. For fonts that include italic faces, these are used when you specify italic. Otherwise, if the face does not exist, you get an oblique font. Oblique fonts are those that slant to the right. In most cases, italic and oblique are the same.
For a style called italics in which all header 1 (h1) tags should be italicized, the code would look like this:
font-variant The font-variant property makes uppercase letters the same size as lowercase letters. The two values are either normal or small caps.
For a style called small that produced small caps, the code would be:
font-weight Specifying the thickness of text is the font weight. The values determine the “thickness” of the text. There are three ways to set the weight: absolute, relative, and numerically.
Relative is based off the current weight as either lighter or bolder. The font weight will be thicker (bolder) or thinner (lighter) than the current weight.
Absolute is either normal, the current default weight, or bold. Of course, bold is similar to bold in a word processor.
Numerically, the thickness can be given as values ranging from 100 to 900. The value of 400 is normal text and 700 is bold. Numbers over 700 are thicker than bolded text, while 900 is the maximum.
Text Properties
Once the fonts are set, then the text is the next major portion of the EPUB seen by the reader. Table 3-4 shows the various text properties.
Table 3-4 Text Properties
text-align The positioning of text can be very important. Paragraphs are usually set as justified to be similar to regular printed books. Chapter titles are sometimes centered. For example, the code to make paragraphs justified would be:
If all header 1 (h1) entries were to be centered for chapter titles, the code would look like this:
text-indent The first lines of paragraphs are usually indented. To specify the indentation amount, the length or percentage must be specified.
What Are the Various Length Measurements?
There are three types of measurements: relative, absolute, and percentages.
Relative measurements are based on the screen resolution or current font size. These measurements will appear differently on various reading systems. The three types of relative measurements are
px (pixels) are the individual dots that make up the display. Depending on the resolution of the display, these can vary quite a bit.
em refers to the width of the lowercase letter m of the current font.
ex refers to the height of the lowercase letter x of the current font.
Absolute values are those that remain the same between all reading devices. They are
pt (point) is comparable to a pixel, but is a standard 1/72nd of an inch.
pc (pica) is based off the typewriter 12-point units, which makes it 1/6th of an inch.
in (inch) is a customary inch.
cm (centimeter) is a metric unit based on 1/100th of a meter, or 10 millimeters.
mm (millimeter) is a metric unit based on 1/1000th of a meter, or 1/10th of a centimeter.
Percentages are related to another factor. For instance, the font size can be a percentage of the normal font size. So, 100 percent would be like the normal-sized text, and 200 percent would be twice the height of the normal text. Likewise, 50 percent would be half the height of the normal text size.
For instance, to make the first line of all paragraphs indented by 5 percent of the total width of a screen, the code would be:
text-decoration The text-decoration property allows for the addition of an underline, overline, or line through the text. There is also an option to make the text blink, but this doesn’t work on most monochrome displays. Since most monochrome displays are not refreshed until a selection is made to turn the page, the blink value does nothing.
To use a style called underlined on any tag so the text is underlined, the code would be:
text-transform Transforming text from one case to another can be useful instead of having to retype sections of a book. The options are lowercase, uppercase, and capitalize. The first two are obvious, but capitalize will capitalize the first letter of each word.
If we wanted to make sure all the chapter titles (h1) were uppercase letters, the code would look like this:
NOTE
Be aware that the capitalize value only works on lowercase letters. If the section being capitalized is already uppercase letters, it will not work.
text-shadow Shadowed text can make a great effect. Unfortunately, like other CSS properties, it is not supported on all reading systems.
The text-shadow property requires four values: x, y, blur, and color. In the CSS style sheet, these values are not separated by commas.
The first value is the x, or horizontal direction. A positive value is to the right, and a negative value to the left. A 0 value remains behind the text.
The second value is the y, or vertical direction. A positive value is down, and a negative value is up. Again, a 0 value remains behind the text.
The third value specifies the length of the blur. The smaller the value, the more clear the color specified next will be. If the blur value is large, the color will become faded.
The final value is the color. The color can be specified as red, green, blue (RGB) values or as acceptable XHTML color names.
For example, you could create a shadow on all header 1 (h1) tags in an EPUB that uses them only for chapter titles. The shadow would be to the right and down by a small bit (.2 em). The blur would be .3 em and the shadow is gray. The code would look like this:
white-space The white-space property is used to determine how whitespace is handled. By using the pre property, extra spaces are kept in a line and not removed. Also, you can specify what happens to text when it reaches the end of the display. The only way to make it wrap at a specified point is use the <br /> tag. The property assures that a line or title remains on a single line.
Assume a line was to keep all the extra spaces, so a style is created called space. The code would be:
If text needed to remain on one line, a style called notwrapped could be made as shown:
letter-spacing If you should need to increase the spaces between the letters in the text, you can use the letter-spacing property. The value given is in any length unit, as previously discussed in the “text-indent” section, except for percent. As with all other properties, the normal value is also available. The normal value is used to set the letter spacing back to the default value. Most all of the properties have a normal value. When a different value is given to change something, these values are inherited by other text. The values must be set to normal to stop the previous change from continuing to the end of the text.
What Is Inheritance?
Inheritance is when a style is applied to a section and all text within the section is then controlled by that style. In a sense, it is inherited from the parent.
For instance, the <body> tag contains all paragraph (<p>) tags. If a style is placed on the <body> tag, then all paragraphs receive it. Let’s assume we assign a style to the body that the alignment is justified. If a small section of text, such as a poem, requires left alignment, we can override the body style and place a left justify on the section. Since left justification is a default, we can simply set the style to normal to undo the justification of the <body> tag.
When some text doesn’t seem to be working properly, change the settings to normal. If this doesn’t work, set the properties specifically to what you need.
Always keep in mind the inheritance of properties within child tags.
If we should want the spacing between letters to spread out a little, we could use the following code:
word-spacing The word-spacing property performs similarly to letter-spacing, except it changes the whitespace gap between words. The gap is set by the font, so both relative and absolute length work. Percent usually does not work for word-spacing.
If you need to increase the gap between words in an EPUB file by 3 em for a style called gapped, you would use the following code:
Page Properties
The page properties allow for the management of page breaks. Table 3-5 shows the various properties for pages.
Table 3-5. Page Properties
page-break-before and page-break-after When you want to start a new page, the best way to do it is to start the new page in a separate XHTML file. Some reading systems do allow for page-break-before or page-break-after to be used.
There are five values for the two page-break properties: always, auto, avoid, left, and right.
The values always, left, and right work the same way. They each force a page break as specified by the property (before or after). Left and right values are used on two-page reading systems that force a break and then make the next page be a left or right page.
The avoid value will attempt to not allow a break at the specified position, but may allow it if it is necessary.
Of course, auto allows the breaks to occur normally, and is a way to bring the page breaks back to normal.
A page-break-before occurs before the element to which the style is attached. For instance, if all header 2 (h2) tags were for chapter titles, the EPUB could be placed in one XHTML file and a style set to cause a page break before each chapter title, as shown:
If a chapter were to end with double <br /> tags, the style could allow for the page breaks to occur after the double tags, as shown:
TIP
The sample code shows a combination of two <br /> tags, demonstrating the special selectors that can be used, which is discussed later in this chapter.
page-break-inside Some elements may require a paragraph to remain as a whole. For example, a quote may require all the text remain on a single page so it can all be read at once without “flipping” the page to finish it. The following code would allow for this in a style called no-flip:
The only two values for the page-break-inside property are avoid and auto. Avoid will prevent a break, while auto allows it as normal.
orphans and widows Orphans and widows are similar in an EPUB. Orphans are the lines of an element left at the end of a page. Widows are the lines left at the beginning of a page.
Let’s assume that we do not want any paragraphs where one line is at the bottom of one page and the rest on the next. Also, a paragraph cannot be on one page with only a single line on the beginning of the next. We would use the following code to achieve this:
The code shows that in the body, all the displayed text in an XHTML must have two lines at the end of a page and at least two lines at the beginning of each page. The number value is the total number of lines required. It, of course, requires that an element, such as a paragraph, have more lines than the value given.
NOTE
As shown in the example code, the properties and values may all be on one line.
Color and Background Properties
The color and background properties allow for the setting of foreground and background colors and images. See Table 3-6 for the various properties.
Table 3-6 Color and Background Properties
color Different colors produce different grays (see Chapter 4) and this is something you need to take into account. Since some EPUB devices are monochrome, setting color options may not produce the desired results. Be aware that if the background is white and the text is lightened, it may be very difficult to read.
Color values are chosen either from a set of XHTML color names or by using RGB values (see Chapter 4). For instance, if we needed a style called red-text that makes the foreground color red, the code would be one of the following:
To use the style on a paragraph, the code would be:
background-color Changing the background color can make things look different, but be careful. If the background color is too dark and the text is black, it may be hard to read. The color values are chosen from a set of XHTML color names or by using RGB values (see Chapter 4).
For example, a style called blue-text sets the background color to blue, as shown:
background-image This property is used to place an image in the background. Remember that this image will be behind the text. If the image colors and text color are similar, the text may be difficult to see.
For example, if an image called image1.jpg is placed on every page within the EPUB, the code would be:
background-attachment The background-attachment property determines how the image is “attached” to the page. One choice is to specify the image as fixed. This causes the image to remain in place as the text is scrolled. The other choice is scroll, which allows the image to move with the text when it is scrolled.
NOTE
Most EPUB devices do not scroll, or move line by line; instead, they page. Paging is the process of displaying a page at a time and moving directly to the next page. If the device pages, then the image should appear at the same spot on every page.
If the image from the background-image example were used and set to scroll with the text, the code would be:
background-repeat When using the background-repeat property, there are four values: repeat, repeat-x, repeat-y, and no-repeat.
To repeat an image over and over horizontally and vertically, use the value of repeat. Repeat-x causes the image to repeat horizontally only, and repeat-y repeats the image vertically. To stop an inherited image from repeating, use no-repeat.
For example, to cover the background with an image called image3.svg, the code would be:
background-position So far, all the settings have placed images in a specific way. If you need to place the image in a specific spot, then the background-position property is required.
The first value allowed is by percentages. The values set are first horizontally and then vertically by percent. For example, if you want an image to appear three-fourths of the way across the screen (75 percent) and then down the screen halfway (50 percent), the code would be:
Another way to specify the positioning of the image is by pixel position along the x and y axes. First the values are listed horizontally (x) and then vertically (y). For example, to place an image 10 pixels to the right and 50 pixels down, the code would be:
Finally, you can specifically place an image using the left, right, top, bottom, and center values. These values have meanings similar to percent, as shown in Table 3-7.
Table 3-7 Positional Values
When using the values from Table 3-7, they are given as horizontal, then vertical. For example, if you wanted to place an image halfway across the screen (center) and way down (bottom), the code would be:
Formatting Properties
The formatting properties allow for the control of elements. Table 3-8 shows the various formatting properties.
Table 3-8 Formatting Properties
visibility Sometimes elements need to be hidden from view. For instance, with Sigil, a table of contents can be created using the headers (h1 to h6) within the XHTML files. If the chapter titles are created using images, then the headers will not exist. Placing a hidden header under the images will allow Sigil to create the table of contents.
When using the visibility property and a value of hidden, the space is still used by the hidden element. A blank line or area where the object was still exists. See the following “display” section for other options to hide elements.
The value of visible will, of course, make the element visible.
The collapse value is used when you want tables to collapse, or hide, a row or column. Simply specify collapse in a style and place it in the <tr>, <col>, or <colgroup> tag.
For an EPUB with image titles, header tags can be placed to help create the table of contents, but they need to be hidden. If the titles are all h2 tags, we can create the following style:
display The display property has values that cover many aspects of XHTML. The none value is used in a similar fashion as visibility:hidden. When the display value is none, the element is hidden, but no space is used. No blank line or area remains as a placeholder. Instead the box around the element is removed.
The block value allows an inline element to be treated as a block element.
What Is the Difference Between Inline and Block?
The concept of inline and block is not too difficult—it just sounds that way.
The block elements create an invisible box around them. The box then can be manipulated to change its dimensions, and the element can be moved around inside the box. Another way to look at it is that a block element has a line break before and after it; for example, <p> and <div> tags.
An inline element fits within another element; for example, <b> and <sub> go in <p>. Inline elements go inside another element and are, therefore, in the same line, or inline.
Block elements are <address>, <blockquote>, <br>, <dd>, <div>, <dl>, <dl>, <h1>, <h2>, <h3>, <h4>, <h5>, <h6>, <hr>, <li>, <ol>, <p>, <pre>, <table>, and <ul>.
Inline elements are <abbr>, <acronym>, <b>, <bdo>, <big>, <blink>, <cite>, <code>, <del>, <dfn>, <em>, <i>, <img>, <ins>, <kbd>, <map>, <q>, <samp>, <small>, <span>, <strike>, <strong>, <sub>, <sup>, <textarea>, <tt>, <u>, and <var>.
When an element is set to block, it basically takes an inline tag and makes it act like a block tag. If you created a style to make all code (<code>) tags behave like block elements, each section of code would now have a line break before and after it. Within the XHTML files attached to the CSS, all code would be on its own line, as shown:
The inline value works the other way, by making a block tag act like an inline tag. For instance, when two paragraphs are placed one after the other, there is a gap between them. If the paragraphs were set to act inline, then the gap would disappear and they would appear as one paragraph. The code shows an example:
Inline-block can be a little confusing. It takes block objects and makes them inline, but still allows them to be treated as a block element. For example, if an unordered list (<ul>) was made and the list items (<li>) were set to inline-block, they would be lined up horizontally. The list items could still be manipulated as they were before, but they would be horizontal, not vertical, as shown in the following code:
The inline-table value allows you to set up a table-like format using inline tags, such as <span>. An example follows:
As shown by this example, all <span> tags would now have a width of 50 pixels and be considered a table format.
The list-item changes an inline item like span to a list item in a list. The elements can then be managed like a list, as shown in the example:
Now all span tags associated with the CSS style will be seen as list items and be preceded by a disc-shaped bullet.
The run-in value allows block elements to join together as one. For instance, if a header tag (<h2>) were followed by a paragraph (<p>) tag, the two would be on separate lines even if both tags were together on one line, as shown:
If a CSS entry made the header 2 tag (<h2>) a run-in, the two lines would now be on one line, as would all other tags following a header 2 tag (<h2>):
The table values work in a similar way as the XHTML table tags. Remember to order them in the same way as is required by the table tag. An example follows that shows a caption and two cells. The first column is set to blue and the second is red. Table headers and footers are not in the example, but they work the same way as the tags.
These CSS types are placed inline to show all the needed properties.
NOTE
Instead of creating a CSS, the properties and values can be placed in the tag like an attribute. It only requires a style= followed by the properties and values separated by semicolons and all enclosed in double quotes. It is best to use CSS on a separate sheet so all settings can be changed in a single place.
position Positioning block items other than with the standard flow can be a little tricky and require a little practice for some. There are four properties for position: static, relative, absolute, and fixed.
Static is the normal or default value. A block item that is set to static will be placed where it normally should be placed. Positioning values such as top, bottom, left, and right have no effect on a static box. Width and height do allow for the box to have a different size. For example, in this code, the line “Static Box” will appear in the normal flow of any surrounding text:
Relative is similar to static, but allows for the use of top, bottom, left, and right, as well as width and height. The box will start at the normal flow position, but then be moveable. In this example, the text “Relative Box,” with dimensions of 50 pixels by 75 pixels, is moved down 50 pixels and to the right 100 pixels:
The absolute value creates an element with its start position based within the container it is in. If it is the main element, it is based off the display, just like a fixed value. If it is inside another element, it is based off that element’s position, as shown. If we use the previous example and place a small box within it that is 20 pixels square and move it down 10 pixels and to the right 20 pixels, we would have the following code:
The fixed value places the element in a moveable box. The box’s position is based on the display as a parent container and not another block element. So the fixed value allows for the element to be placed anywhere on the screen, even over other elements.
float The float property has three values: left, right, or none. None is the default and all blocks act normally.
If left or right is used, then the element boxes are moved to the right or left of the container that the element is inside. Float can be used with the position property to cause the box to move to the left or right of the parent container. We can use this property to float text around an image. The text is floated right and the image is floated left. The image tag is placed within the text, not before or after, the text will flow around the image, as shown in the following code:
This isn’t the best way to get text around a box, but that is covered more in Chapter 4.
z-index Z-index values can either be a number or set to auto. Images placed in a display at specific coordinates (absolute or fixed) can overlap one another. The images can then be given a depth value to place certain images on top of others. Images with a value of –1 will be placed behind text and act like a background image.
When the value is set to auto, the z-index value for the image is the same as the container it is in. For example, to place an image as a background image, the Z-index would be –1, as shown:
vertical-align Vertical alignment controls the vertical placement of inline elements. Using CSS lengths, the element can be raised (positive value) or lowered (negative value). Percent can also be used to specify its distance compared to the line height.
Other values include the baseline. The baseline is the default to which the bottom of the text is placed. Another value is bottom. This refers to the lowest element on the line. Middle is the center of the parent container. The value sub makes the element act like a subscript, while super makes the element act like a superscript. Text bottom is the bottom of the parent container’s font, while text top is the top of the parent container’s font. Top places the top of the element even with the top of the tallest element on the line.
If, for example, we needed a span to be called centered so we could align the text within the span to be vertically centered, the code would be:
top, bottom, left, and right These properties are used to place elements in specific locations when using the position property. The values may seem a little strange at first, but it isn’t too hard to catch on.
Top places the item at the top, but the value given, whether it is length or percentage, is how far down from the top. The left property specifies how far from the left, and so forth. If an element must be at the top of a parent container, then the value would be 0px, or 0 percent. Negative values are allowed, and none of the properties work on static positioning.
To make a header 1 (<h1>) tag’s position absolute and then move it up 10 pixels from its normal flow position, the code would be:
clear The clear property lets you specify whether floats are allowed to the sides of the current element. The property clear has four values: none, left, right, and both.
None declares that no clear is present and floats are allowed on either side of the element. Left specifies that no floats are allowed on the left side; right disallows floats on the right side. Both removes floats from both sides of the current element. If an image is floated to the left of text but the next paragraph should be moved to the image’s bottom and then displayed, the paragraph should be cleared of floats, as shown:
overflow Sometimes when specifying the box size, the box may be too small for the content. This produces overflow. The default value is visible. Visible shows all content, even that which is outside the box. If the box has a background color or a border, it will be obvious that the content has overflowed.
Hidden is another value that will hide the overflow; unfortunately, this causes the missing content to not be viewable.
The value of scroll places scroll bars to allow the reader to scroll the content to view it.
NOTE
Be aware that scroll bars do not work on all EPUB devices.
The auto value clips off the overflow and places a scroll bar on the box to view the overflow.
The example that follows creates a green box and places text within it. The overflow property is set to scroll and causes scroll bars to appear.
clip If an image is too large for its containing box, the clip property allows you to clip an absolute positioned image. If the overflow property is set to visible, then clip does not work. The auto value is the default and causes no clipping to be applied to the image.
The rect value allows you to specify a rectangular area. The values are top, right, bottom, and left. The top value is the number of pixels from the top to clip off. The right value is the number of pixels from the left to keep (the image portion after the number of pixels is clipped off). Then the number of pixels from the top to the bottom is specified and the bottom section is clipped off. Finally, the left side indicates the number of pixels from the left to clip off.
For example, if we have an image that is 200 pixels wide and 100 pixels tall and we want to clip off 10 pixels all around the image, keeping only the center, the code would be:
Table Properties
The table properties allow for the control of table elements. Table 3-9 shows the various table properties.
Table 3-9 Table Properties
table-layout In some cases, each cell in a table will have different widths. The width of the table can be fixed or allowed to shrink or enlarge as needed.
When the value of table-layout is set to auto, the column width is determined by the widest cell in the column—that is, the unbreakable part that has no spaces. Text in cells can be split at spaces, hyphens, and other elements.
The value of fixed sets the column widths to be able to account for them all within the table width.
The following example shows a style called fixed-table that has a fixed width:
border-collapse The border-collapse property allows you to set up a table where each cell has its own border, or, if adjacent cells, they share the same border. To have separate borders, use the value separate. For cells to share a border, use collapse.
The following example shows a style set for all tables to have the borders collapsed and therefore shared by all cells:
border-spacing When table cells are set to have separate borders, the gaps between the borders can be controlled. The border-spacing property can have one length (cm, px, pc, etc.) specified or two. If one length is specified, then it is used for both horizontal and vertical spacing of borders. If two lengths are specified, the first is for the horizontal spacing and the second for vertical spacing.
For example, if all tables were to have a 5-pixel horizontal spacing and a 10-pixel vertical spacing, the code would be:
empty-cells Another property useful for a table with separate borders is empty-cells. When a cell is empty, this property allows the cell and its background to be either hidden or shown. The default is for the empty cell to be shown, or with the value of show.
To hide the empty cell, use the value of hide. A cell is considered empty if the cell has no content; has its visibility property set to hidden; or contains tabs, line feeds, or blank spaces.
The following example shows a style set to hide all empty cells in all tables:
caption-side The caption-side property is used to specify the location of the table caption. It can be placed on the top or bottom of the table. Usually only top or bottom is allowed, but some systems do allow the value of left or right.
NOTE
Stick to top and bottom since some reading systems may not support the left and right values. If a system does not support left and right, then the caption should appear at the top by default.
The following example shows all table captions set to be at the bottom of the table:
List Properties
The list properties allow for the control of list elements. Table 3-10 shows the various list properties.
Table 3-10 List Properties
list-style-type When lists are made, each list item (<li>) can be preceded by a bullet as we saw in Chapter 2. The style of the bullet can be changed as shown in Table 3-11.
Table 3-11 CSS list-style-types
The following example sets all bullets to lower roman for all tables:
list-style-image Instead of using a built-in style, you can supply an image of your own to use. All that is required is a supported image type (PNG, GIF, JPG, or SVG). It is best to use a small image with a width of 1 em and a height of 1 em. The width can be more, but it is best to keep the image size more of a square. Of course, the 1 em is based off the current font being used. Technically, any image will do, but the smaller ones work better. The larger the image used, the larger the space that appears between the list items.
The following example uses an image called arrow.jpg for all unordered lists (<ul>):
list-style-position The position of the list style can be inside or outside the element’s box. By default, the position is outside the element box.
The following example specifies that all list items (<li>) will have the list styles placed inside the element box:
Link Properties
The link properties allow for the control of links. Table 3-12 shows the various link properties. Technically, these are not properties, but specific style names.
Table 3-12 Link Properties
a:link The a:link, a:visited, and a:active styles allow you to specify color, fonts, sizes, etc., for a link. The three must appear in the order shown in Table 3-12.
For example, to specify that a link should be blue and bold, a visited link should be green and italics, while an active link should be purple and normal, use the following code:
NOTE
On a monochrome EPUB display, the color makes little difference, but other properties may be set.
Box Model Properties
The box model properties allow for the control of dimensions, margins, padding, borders, and outlines. Table 3-13 shows the various box model properties.
Table 3-13 Box Model Properties
Figure 3-2 shows a sample box. The center is the content, such as an image, header, paragraph, or other element. Around the content is an area that is padding. The padding separates the content from the border, however thick the border may be, if it exists. Outside this section is the margin that separates the content and border from other objects. Surrounding the margin area, if it exists, is the outer edge of the box. Even when a border is placed around content, it doesn’t include the margin area. When margins are set to 0, then borders can touch.
For all of the properties listed in Table 3-13, keep Figure 3-2 in mind to better understand the concepts that deal with it.
height, max-height, and min-height These properties affect block-level elements to specify the height, maximum height, and minimum height of a block. The measurements specified only affect the content and not the padding or margins. The maximum height specifies the maximum height of the box, and the minimum height is the smallest the box can be. If the height goes beyond these boundaries, then the value will stop at the minimum or maximum.
All three values can be given as lengths or percentages, as discussed previously in this chapter under “What are the four ways to specify size?”. Height also has an option for auto. Auto allows the size to be calculated automatically for the size it needs, if the container it is inside can hold it. Max-height has a possible value of none which is default and allows the height to go to any value. Min-height has a default value of 0.
NOTE
Content out of the defined box is controlled by overflow values.
If the height of a division is set to 100 pixels and the overflow is set to clip off any extra part of the image after 100 pixels, the code would be
width, max-width, and min-width These properties affect block-level elements to set the width, maximum width, and minimum width. Measurements do not affect padding or margins, only the content portion of the box. The maximum width sets the maximum value of width and minimum width sets smallest value of width. Minimum width by default is 0 while maximum width default is set to none. If width should be larger than the maximum or smaller than the minimum, the width will be set to the max or min value as needed. All three values can be given as lengths or percentages as discussed previously in this chapter in the “What Are the four Ways to Specify Size?” sidebar. Width also has an option for auto. Auto allows the size to be calculated automatically for the size it needs, if the container it is inside can hold it.
NOTE
Content out of the defined box is controlled by overflow values.
If a division were made with a width of 75 percent and the overflow is shown, the code would be:
margin-top, margin-bottom, margin-left, margin-right, and margin Values can be set to modify the margin for the box. They can be set for each side as needed. The auto value is used to allow the reading system to determine margin values to allow the box to fit in its container.
For example, if all images in an EPUB were to have a margin of 2 pica all around it, the code would be as follows:
If all margins were to be the same, then the property margin can be used with one value for all sides, as shown:
If the margins are somewhat different, they can be specified as top, right, bottom, and left. The values start at the top and continue around the box clockwise. The following example sets an image margin for the top and bottom of 3 em, a left margin of 5 pt, and a right margin of 3 percent, as shown:
padding-top, padding-bottom, padding-left, padding-right, and padding The values for these properties specify the padding on the relevant side of the box. The value is either a length, as discussed earlier, or a percentage of the parent container. The default padding value is 0.
If a paragraph were to have padding above and below set to 5 em and padding to the left and right of 15 percent, the code would be:
Padding also has a property called padding that allows you to set all four sides at once if the padding values are the same, as shown:
Padding also allows for all four sides to be set starting at the top value, then moving to the right, bottom, and left. If, for example, the padding for an image was to be 1 inch for the top, .5 inches for the bottom, 3 em for the right, and 2.5 em for the left, the code would look like this:
border-top-color, border-bottom-color, border-left-color, border-right-color, and border-color The color is set individually for each side. The color can be specified with an RGB value or a supported color name. The default value is transparent, which causes the border to allow the background to come through.
In the following example, the top is red, the bottom is black, the left is blue, and the right is green:
The border color can specify all sides at once, or specify all four sides, starting with the top and going clockwise around the box. For example, if you wanted all sides to be blue, the code would be:
If all sides are different, we can use a previous example. For an image border, if the top is red, the bottom is black, the left is blue, and the right is green, the code would be:
border-top-style, border-bottom-style, border-left-style, border-right-style, and border-style The border style can be specified for each side or all sides at once. The border styles are listed in Table 3-14.
The following example indicates a border around all division sections but no border to the left or right and a single solid border on top with a double line on the bottom:
Use a single value to place a border on all sides of the box. The following example shows a dotted border for all sides:
If each side is to be specified individually, then the style names can be used, starting with the top and going around the box in a clockwise direction, as shown:
border-top-width, border-bottom-width, border-left-width, border-right-width, and border-width To set border widths, the border style must be set, since it defaults to none. The width is given as thin, medium, or thick and can also be specified by CSS length values. Percentages are not allowed.
For example, to set the width of an image for the top and bottom to 3 pixels and the left and right to 2 em, the code would be:
To specify all sides, starting with the top value and going around the box in a clockwise direction, the code would be:
If all sides are to be the same, such as 3 px, the code would be:
outline-style The style for the outline is similar to that for a border. See Table 3-14 for the style names.
For example, to set a ridged outline around all tables, the code would be:
TIP
Since the default outline style is none, always set the style first for an outline, and then set color and/or width.
outline-color An outline is similar to a border except that it overlays the box and takes up no room. So this means that the outline does not add height or width to the box. The outline appears outside the border, touching it. Regardless of the thickness of the border, the outline is still outside it.
The outline-color property is used to specify the color of the outline in any of the aforementioned ways. Invert can also be used to invert the color, making sure the outline is visible.
For example, to specify an outline around an image that is blue, the code would be:
outline-width Borders can have a width specified, and so can outlines. The values are thin, medium, thick, and the normal CSS measurements, except percent.
To set an outline around a specific paragraph called outlined that is a solid style and a width of 1 em, use the following code:
Special Selectors
Many selectors have been covered already, but a few more exist that enable you to perform some fancy CSS manipulation. If you come across something you may not understand in CSS, it most likely is some type of selector (unless it is in curly brackets).
ID Selector
The ID selector is another type of “normal” selector. It works just like the class selector, but works with ID attributes.
ID styles in CSS start with a pound (#) sign. The style is then assigned (without the pound sign) as an ID value. For example, if an ID selector is named bold-text and then applied to a paragraph, the code would look like this:
All Tags
All tags can be selected by using the asterisk (*). Be aware that this affects every element connected with the CSS style sheet. For example, if we wanted all text to be green, the code would be:
Multiple Elements
If multiple elements will have the same settings, such as header 1 (h1) and header 2 (h2), they can be separated by commas. We can place as many elements as we want together as long as they are separated by commas. For example, let’s make h1 and h2 elements underlined, as shown:
Child
If you want to put styles on elements that only exist with other elements, you can use the selector element1>element2. Here, element2 must exist within element1. For example, if you wanted all image elements within a division to have a yellow outline, the code would be:
Descendant
You can manage an element within another element, such as italics (<i>) within a paragraph (<p>). We can then make the italicized element a larger font as follows:
Adjacent Sibling
If every element after another element needed special styles, it can be done using element1+element2. Here, element2 must follow directly after element1. For example, in an EPUB, if chapter titles are header 2 (h2) and the first paragraph after the header should have no indentation, the code would be:
If you needed to indent the second paragraph after the header 2, not counting the one directly after it, you would use:
Attribute and Value
To find a specific value of an attribute, you can search for a match. For example, you can search for all tags with a property of title that is set to MonaLisa, as shown:
If we wanted to select and apply a style to all tags with a partial attribute and value, we can use this selector. For instance, to find all tags with the language beginning with “fr,” we can apply an italics style, as shown:
We can also check for text contained in the value by using ~=. The selection must be an exact match—partial matches do not count. If the search is for “frog,” for example, “frogs” will not be found, although “green frog” will. If we wanted to select all tags with a title containing the word “frog” and create a border around it with a thickness of 2 px, the code would be:
Values may also begin with specific text. For instance, to find all tags that have a class beginning with “text-” and highlight them in yellow, we can do the following:
If we want to change the style for any attributes that end with specific text, such as any JPG files that can have a border, we use the following code:
We can also find values that contain specific text in the middle. For example, if links to McGraw-Hill.com needed to be underlined, the code would be:
First Letter
To select the first letter of a specific element, such as a paragraph tag (<p>), you use element:first-letter. For example, to make the first letter of all paragraphs a bold font, use the following code:
These selectors can be combined. For example, if an EPUB had all chapter titles as header 2 (<h2>) and the first letter of each paragraph right after the header should be made twice as big as the other letters, the code would be:
First Line
Similar to first letter, the first line element affects the entire line. The actual portion of the line may vary, depending on the reading device, since default font size, screen size, etc., may cause the first line to vary in length. Again, note that the selectors can be combined.
For example, for any paragraph following a header 2 (<h2>), we can cause the first line to have an overline as shown:
First Child
The first child element is the first occurrence of a specific tag within another element. In the following example, the first paragraph tag that occurs in the body and any div tags should be orange, as shown:
We can also style the first bold (<b>) tag in each paragraph to be underlined, as shown:
In addition, the first child of each ordered list can be bold:
Content Before and After
Content can be placed before and after specific elements. If text needed to be placed after tags, for example, and you did not want to have to do it manually, you can use this property instead. If all of the header 2 (<h2>) tags need to have -= placed before it and =-after it, the code would be:
Within the curly brackets, other styles can be set for the content to be added, such as color, font weight, etc.
General Siblings
To style every element after another element of specific types, use the general siblings selector. For example, to style every paragraph after a header 2 (<h2>) to be indented by 2 em, the code would be:
This will indent every paragraph after the header that is not part of a <div>. The style will continue to the end of the XHTML file.
First of Type
First of type is used to set styles for elements that are the first of its type within a parent. For example, if every first emphasis (<em>) element is to be underlined as well, use the following code:
Last of Type
Last of type is used to set styles for elements that are the last of its type within a parent. For example, if all final emphasis (<em>) elements are to be overlined as well, use the following code:
Only of Type
If only one tag is used within a parent, you can set styles for that element. For example, if you wanted the only <strong> element to have a line through it as well and a parent, such as a paragraph, has only one <strong> element, the code would look like this:
Only Child
The only child selector sets a style for the specified element that is the only child element of a parent.
A style is set up where the paragraph (<p>) is being looked for as the only child within an XHTML file. If a span (<span>) and (<p>) paragraph exist within a division (<div>), then neither is the only child and both are ignored. If a division (<div>) has a paragraph (<p>) only, then the paragraph would be given the style. The code would be:
nth Child
The nth child element allows you to specify odd or even and apply a style to those items. It is best used with lists and tables that are set up in a linear fashion and do not have extra elements mixed in. In an EPUB, if I specified the even paragraphs (<p>) to be red and the odd ones to be blue, they may not be every other one as expected. The nth child counts all elements, not just the specified tags. An algebraic formula is used to specify the selected items otherwise. For example, if every third paragraph were to be blue, the code would look like this:
Instead of specifying 3n, you can use odd or even, as long as you keep the aforementioned caveat in mind.
nth of Type
The nth of type is a very useful tool that we’ll talk about more in Chapter 4. The nth of type element works similar to nth of child, but it only counts the specified selector. This way, you get exactly odd and even when you want it.
For example, if every even paragraph is blue and the odd ones are purple, the code would be:
nth Last Child
Instead of selecting every so many children, you can select the last item or the nth last element. For example, to apply a style to a paragraph that is the third last paragraph, use the following code:
If no number is specified, the very last selector type is selected. Like nth child, this selector counts every element, not just the specified types, as explained in “nth Child.”
nth Last of Type
Similar to nth last child, this picks only a specified type and does not count every element. Otherwise, it works the same as nth last child.
We’ll use the same example to demonstrate this, but depending on the paragraphs and elements involved, they may change the color of different paragraphs, as shown:
Last Child
The last child selector allows you to select the very last element of a parent. Be aware that if the last element is a break (<br />), no visible changes could be made, since this element has no visible attributes. If the selected element is not the last element, then nothing happens.
Root
Root allows you to set CSS settings for all the XHTML files connected to the CSS style sheet. The :root selector specifies settings to place on the <HTML> tag that affects the entire file.
For example, to set all margins to a default of 5 pixels, use the following code:
Of course, this is a simple example, but as many settings as you wish can be placed in the brackets to set up your XHTML files within the EPUB.
Empty
To select all empty elements of a specified type, you can use the empty selector with the required tag. For example, if you wanted to find all empty paragraph tags and remove them from the display (meaning no line break), use the following code:
Practice
I know this chapter may seem overwhelming if you do not know CSS. Be aware that you may not use many of the properties and selectors discussed here, but it is helpful to be familiar with them. In the following chapters we’ll go over examples that will help you to understand CSS much better. Keep referring to the EPUB tester file from McGraw-Hill’s website. You can view it in Sigil to see how things work. You can also change things in the tester to try things out. Just remember to keep a backup copy or to discard the changes when you exit Sigil.