Introduction

Chapters

Strategy Resources Structure Style Layout Composition Production Infrastructure

Appendices

E-Book Formats Explained Image Formats Explained Advanced Styling & Layout Better Photography Working with SVG Unicode and All That Troubleshooting

Supplementary

Revenue Calculator Contact
Copyright © Dodeca Technologies Ltd. 2016

Layout

The previous chapter explores the basics of styling an e-book using CSS, and focuses on the essentials that most authors require in that respect, if indeed they choose to apply their own styling, as it is not a mandatory step. If you do not intend to apply styling to your content, you can skip this chapter and progress to the next chapter, Composition, which considers the creative decisions you need to make during production.

If you do choose to style your content, however, you may need to take a more-advanced approach that goes beyond the relatively simple cosmetic techniques covered in the previous chapter. This is likely if you are producing a book of a more technical nature, and so this chapter explores the manipulation of spatial relationships between content elements, a concept that we know commonly as layout.

Note here that, as the previous chapter points out initially, you may consider issues such as element backgrounds and shadows to be non-positional factors, and thus do not belong in this chapter. However, they relate closely to what is known as the ‘box model’, which makes them easier to address here.

Flow Types

The central factor to understand when considering the positioning of elements in a page is that CSS defines a number of content types (or ‘flow types’, if you prefer). This relates to the ways that content elements behave in relation to each other on the page, and there are two principal types, inline elements and block elements (and note that you should not confuse inline elements with inline CSS definitions, which the previous chapter​considers).

The sidebar depicts the difference between the two, and shows that inline elements ‘seek’ always to abut to the lateral trailing-end of the previous element in the content – you can think of a sequence of consecutive inline-level elements as forming a snaking string that wends its way down the page.

To see this in the flesh, consider the following example, which highlights three inline elements amongst the rest of the content:

Lorem ipsum dolor sit amet, consectetur adipiscing
elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. <b>Ut enim ad minim
veniam</b>, quis nostrud exercitation ullamco
laboris nisi ut aliquip ex ea <i>commodo
consequat</i>. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum
dolore eu fugiat nulla pariatur. Excepteur sint
occaecat <img src = 'Images/LoremIpsum.svg'/>
cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in la pariatur. Excepteur sint Lorem Ipsum place-holder
         graphic occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

This shows that elements like <b>, <i> and <img> elements follow the pattern shown in the upper half of the diagram above. The user agent generates no line-breaks between them, and they form a single continuous flow.

To complement those inline elements, there is also a general-purpose element called a <span> that the previous chapter​mentions. As shown there, spans impose no formatting (other than inline flow) on the content they enclose, and thus they provide a way of styling a run of text arbitrarily, as the section in the previous chapter shows.

In contrast, block-level elements act as if there was an invisible <br/> between them (as the lower half of the diagram above depicts). That is, the presence of two consecutive block-level elements causes the user agent to break the flow between the two, to lay them out down the page, and to expand them so that they take up as much lateral space as possible. You could say that block-level elements act as if they prefer seclusion along the horizontal axis.

The next example, given first in Chapter Three, Structure, shows block level elements in operation:

<p>Lorem ipsum dolor...</p>

<p>Ut enim ad...       </p>

<p>Duis aute irure...  </p>

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.

This shows that <p> elements conform to the block flow-model, where the user agent inserts a line-break between them and other adjacent elements in the HTML. Other block-level elements include <ol>, <ul> and <table>, and, as with <span>, HTML supports a general-purpose element called <div> (short for ‘division’). This, like <span>, imposes no formatting other than block flow, which generates a vertical break between a given <div> and adjacent elements.

Divs allow you to create ‘containers’ for other elements (inline and/or block), such that styling and positioning of the parent <div> applies to all child elements contained within (the concept of inheritance, as​covered in the previous chapter). It also allows you to position elements of your content collectively, as shown​in Chapter Six, Composition.

Box Model

To complement the concept of flow types, CSS defines anatomies for inline and block elements, called collectively the ‘box model’, and the diagram below depicts the inner structure of an inline element.

Diagram of inline-element box model

Compare and contrast that with the next diagram, which shows the inner structure of a block-level element.

Image of block-element box model

These show that user agents render every element as a block that has a background colour or image, and may have a border. All elements have padding to their top, right, bottom and left, the extent of which may be zero, and they all have a right and left margin, which may also be zero.

Note here that the difference between padding and margins is that the padding exists on the inside of any border, and any background colour or image occupies the content area up to the extent of the padding. Margins, on the other hand, operate on the outside of any border, and do not include the background colour and/or image.

Note too that these principles apply to images as well, as even they can have a background of some form. This may seem counter-intuitive, but images can have padding just like any other element, and so any background that is set for a given image will fill any padding that it may have.

These commonalities aside, there are three principal differences between the two models:

1.

i.

Non-replaced inline elements (<b>, <i>, <span> etc.) do not have a top and bottom margin, whereas block elements do. However, replaced inline-elements like images can have top and bottom margins, which complicates matters.

ii.

The CSS standard muddies the waters still further, in that it is possible to emplace the tag-language code that comprises an SVG image directly into a given tract of HTML (an issue that Appendix E considers). In this case, the image element is most-definitely not of the ‘replaced’ variety as it is integral to the HTML, and yet still behaves as a replaced inline element in that it can have top and bottom margins.

These last two points comprise probably the most convoluted technicality that you will encounter in this entire guide. Happily, they impinge on the aims of only a small proportion of e-book producers (those developing technical works such as this), and even then they pose no cause for concern.

2.

Padding in an inline element affects the horizontal positioning of adjacent elements in the flow, but while increasing vertical padding increases the vertical extent of the background, and thus the length of any vertical borders (see below), it does not increase the effective height of the element.

3.

Block elements respond to the CSS width and height properties, whereas non-replaced inline elements respond instead to the line-height property, which the previous chapter​covers. In essence, the line-height property in inline elements plays the role that vertical margins play in block elements.

As well as the width and height properties, CSS defines a range of others through which you can manipulate padding, borders and margins, a subset of which the labels in the diagrams above enumerate. Note, however, that there are so-called ‘shorthand’ properties, such as margin, padding and border, where you can set values for (for example) the top, right, bottom and left margins using just a single rule. These are an alternative to using (to continue the example) the individual margin-top, margin-right etc. properties, and can help therefore to cut down on code verbiage. The relevant sections below cover these on a per-property basis.

Despite this, however, shorthand properties like background, are so complex in the number of values they take (which must conform to a specific order too), that you are better off saving yourself an additional challenge by using the individual background-image, background-position etc. properties instead.

Before considering specific box-model-related properties in the sections below, a few other points are pertinent:

1.

Changing Flow Type. You can change an element's flow type using the display property. That is, the following:

display : block;

…coerces an element to conform to the block flow-model, whereas the following:

display : inline;

…yields conformance to the inline flow-model. It is better to do this only sparingly, and to go with the defaults where possible. This will avoid the confusion that can arise when, say, a given <span> (which, normally, has a flow type of inline) appears to be misbehaving because it is exhibiting block-type dynamics.

2.

Other Flow Types. CSS defines a number of other layout types, such as inline-block. This is a halfway house between inline- and block-level elements, in that such elements do not disrupt the lateral flow, but padding and margin rules yield the effect that they have on block-level elements.

Other types that the standard defines, such as list and table, go beyond the scope of this text, and so you should consult a comprehensive reference should you need information on these, although do note that they are unlikely to be of value in e-books, and that e-readers may not support them either.

3.

The box-sizing Property. Normally, the width of an element means the width of the content area, inside of any padding and margins. However, this is not really the way we think of width when positioning elements (such as when using the float property). Width in that case means the overall width of the element including any padding and borders.

Given this, CSS supports the box-sizing property, which allows you to change the way the width property works. If, for example, you state the following:

box-sizing : border-box;

…then the width you set for the element to which that above rule is applied will be its overall width, where the width of the content area will be the width you stipulate minus the width of any right/left borders and padding (the equivalent applies to the element's height). Amazon's documentation is silent on this property, but it does work on Kindle devices. If you wish to explore this property further, the search-terms suggestion is:

css ‘box-sizing’

With these points in hand, the next few sections consider each of the elements of the box model, working from the inside out.

Backgrounds

You can give an element either a colour or an image as a background. For example, the following code sets a dark grey background on an element, and gives the text a correspondingly light colour in order to maintain visibility:

p.DarkGreyBackground
   {
   color      : #E0E0E0;
   background : #404040;
   }
<p class = 'DarkGreyBackground'>
Lorem ipsum dolor...
</p>

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Alternatively, you can give an element an image for a background, as the next example shows:

div.TexturedBackground
   {
   background-image : url('Images/TexturedBackground.png');
   color            : #FFFFFF;
   }     
<div class = 'TexturedBackground'>
   <p>
   Lorem ipsum dolor...
   </p>

   <p>
   Ut enim ad...
   </p>
</div>

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Note that, if a graphic is too small to fill an element's background, the user agent will tile it repeatedly across and down to fill the entire background area. You can prevent this by using the background-repeat property, which the section below covers in its discussion of padding. You can also offset a background image along the horizontal and vertical axes, as is also covered in the same section below.

Note that CSS also supports the idea of multiple background images, where you give the background-image property a set of values, separating each with a comma. This is useful in web site development, and, for some producers, would therefore be of value in generating e-books. Unfortunately, it is not supported on Kindles currently, even though there is at least one extant book on e-book production that states incorrectly that it is. This means that you can give an element a single background image only.

A final point in this section: a colour ‘gradient’ is an area of colour that changes from one shade to another down and/or across an element. In support of this concept, CSS defines a linear-gradient value-specifier, which is a welcome alternative in web site development to using an equivalent background image. The EPUB format supports this feature, but KF8 does not, although it is notable that gradients are possible in SVG images, which is a feature of that vector format that Kindles do support. See Appendix B for more on this point.

Widths & Heights

Normally, you do not need to worry about the width and height of an element in an e-book, as most books have an exclusively linear flow down the ‘page’, where each element (usually headings and paragraphs) fills the space completely along the horizontal axis. However, centring an element calls its width into question, as does positioning an element using the float property. Moreover, images have an implicit width, which raises the question of how you make them fill the display, irrespective of whether the user agent is set to display a book in portrait or landscape mode.

Setting the width of an element is simple. You use the width property, where you should use either ems or percentages as the units (which the previous chapter​covers). For example:

p.Narrow { width : 35%; }
<p class = 'Narrow'>
Lorem ipsum dolor...
</p>

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

In this case, the CSS code states that all paragraphs of class ‘Narrow’ should be 35% the width of their parent element. This means that, to make an image fill the page irrespective of the graphic's native size, you should set its width to 100% (assuming that its parent is the <body> element, or that any chain of parent, grandparent etc. elements above it also has a width of 100%).

For example, a graphic rendered at its native size of 85 × 85 pixels, looks like this on your e-reader:

Lorem Ipsum place-holder graphic

However, by applying the width property with a value of 100%, we can make it fill the page, as the next example demonstrates:

img.FullWidth { width : 100%; }
<img class = 'FullWidth' src = 'Images/Graphic.svg'/>
Lorem Ipsum place-holder graphic

Note that (and without trying to pre-empt the coverage below of floating elements in CSS) the height property has no effect on block-type elements when they are subject to the default positioning mode, where elements flow to the right and down the page.

Note too that setting the width of an element does not imply or force any ‘clipping’ of its content. Consider the following, where a child <div> has a width that is greater than the width of its parent:

div.Parent
   {
   background-color : #E0E0E0;
   width            : 13.0em;
   }

div.Child
   {
   background-color : #707070;

   width            : 15.0em;
   height           :  2.0em;

   padding          :  0.5em;

   }
<div class = 'Parent'>

   <p                  >Lorem ipsum dolor          </p>
   <div class = 'Child'>Sit amet                   </div>
   <p                  >Consectetur adipiscing elit</p>

</pre>

Lorem ipsum dolor

Sit amet

Consectetur adipiscing elit

That is, content that has its own width (implicitly, as in an image, or set explicitly) does not push against the boundary of its containing element, causing it to expand in order to preserve containment (an issue that can cause some consternation when you are new to CSS).

Normally, this is not an issue with textual content, as a user agent will flow the words such that they remain within the boundary of their containing element, but <pre> elements (considered in​Chapter Three, Structure), where all whitespace is preserved, exhibit the same effect, as the next example shows:

pre
   {
   width            : 13em;
   background-color : #E0E0E0;
   }
<pre>

Lorem ipsum dolor sit amet, consectetur.

</pre>

Lorem ipsum dolor sit amet, consectetur.
         

As you can see, the text protrudes to the right of the <div> element, and the solution in both cases, assuming that the protrusion is not what you want, is to use a CSS property called ‘overflow’. The CSS specification defines this property as taking one of six values, but the one in which we are interested as e-book producers is ‘hidden’. Given this, we can modify the parent/child example above as follows:

div.Parent
   {
   background-color : #E0E0E0;

   width            : 13em;

   overflow         : hidden;

   }

Lorem ipsum dolor

Sit amet

Consectetur adipiscing elit

…which clips the child <div> (and note that this would have the same effect if the child were an image rather than a <div>). overflow also works with text, and will clip it in the same way. However, we may wish to indicate to the reader that there is more text than can be displayed, and so we can use the text-overflow property in conjunction with overflow, and give that property a value of ‘ellipsis’, as the next example demonstrates.

pre
   {
   width            : 13em;
   background-color : #E0E0E0;

   overflow         : hidden;
   text-overflow    : ellipsis;

   }     
<pre>
Lorem ipsum dolor sit amet, consectetur.
</pre>

Lorem ipsum dolor sit amet, consectetur.
         

As the section on Terminology and Notation in the introduction, documents,​this guide employs this technique in order to prevent code listings from over-running the edge of its code examples, but do note that some varieties of the Kindle brand exhibit a rather nasty bug in relation to this property, which is documented​in Appendix C, Advanced Styling & Layout.

Padding

As explained above, an element's padding sits between its content and its border, if it has one, and you set the extent of the padding in just the same way as you would the width and height. Remember that, if you use percentages, any number you give means a proportion of the enclosing element's width or height, whereas using ems means a proportion of the font size for that element (which it will​inherit from its parent in the absence of an explicit font-size rule for the element in question).

For example:

p.TexturedBackground_Padded
   {
   background-image : url('Images/TexturedBackground.png');
   color            : #FFFFFF;

   padding-top      : 10%;
   padding-bottom   : 10%;
   padding-left     : 20%;
   padding-right    : 20%;

   }
<p class = 'TexturedBackground_Padded'>
Lorem ipsum dolor...
</p>    

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

As the box-model section above points out, you can use shorthand properties to apply rules for padding, borders, margins etc., and the shorthand equivalent of the example above looks like this:

p.TexturedBackground_Padded
   {
   background-image : url('Images/TexturedBackground.png');
   color            : #FFFFFF;

   padding          : 10%; 10%; 20%; 20%;

   }     

…which is to say that you can give all four values for padding in one rule. Do note that there is a strict order of specification, which is top, right, bottom, left. In other words, the ordering is as if you were working clockwise round the points on a navigational compass: North, East, South and West. This ordering is the same for all equivalent shorthand properties.

a.Link_Forward
   {
   background-image    : url('Images/Link_Forward.svg');
   background-repeat   : no-repeat;
   background-position : right top;
   background-size     : auto  0.4em;

   padding-right       : 0.9em;

   }     
Lorem ipsum

<a href  = 'Chapter_42.htm'
   class = 'Link_Forward'
   style = 'text-decoration : none '>dolor</a>

sit amet ... ea commodo consequat.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

This example reprises the point​made in the section above on the box model that it is easier to manipulate background characteristics in a piecemeal fashion by means of the individual background- properties, than it is to use the shorthand background property. Note therefore the ‘no-repeat’ and ‘right top’ values for the background-repeat and background-position rules respectively. These tell the user agent that the graphic must not tile across the element, and that it must appear at the element's top-most right-hand side.

Aside from those points, the background-size property, predictably, sets the size of the image, so that it matches the size of the text. Here the ‘auto’ keyword tells the user agent to set the horizontal extent of the graphic to whatever will preserve the aspect ratio,​given that the code stipulates a width of 0.5ems.

Note also the padding-right : 0.9em rule, which extends the content area of the element right-wards to make room for the link graphic. Unfortunately, that creates a noticeable gap between the end of the link text and the next word, as you can see in a repetition of the demonstration above:

Lorem ipsum dolor sit amet...

One solution here is to apply a negative margin-right rule (see below), but some user agents may not support that, or they may implement it incorrectly. A simpler solution therefore is to remove the space between the link element and the following word. For example:

Lorem ipsum <a ... >dolor</a>sit amet...

Lorem ipsum dolorsit amet...

However, while this closes the gap, it also causes the user agent to see ‘dolor’ and ‘sit’ as a single word, which will fool its text-flow mechanism and cause unsightly gaps to appear at the end of a given line of text when ‘sit’ is the final word on that line.

The solution is to use the zero width space character that Unicode defines, the decimal​codepoint for which is 8203. Placing that between the link element and its following word closes the gap between the link element and the following word, while the padding applied by the CSS maintains visual separation. The user agent, however, still sees the element and following word as separate entities, which preserves correct re-flowing of text.

For example:

Lorem ipsum <a ... >dolor</a>&#8203;sit amet...

The use of padding and background images also allows proper control over the use of custom list-item markers. As the previous chapter​explains, the list-style-image property is of little value, and so the best approach is to apply the list-style-image property with a value of ‘none’, and to use a suitably-positioned background image instead.

The next example demonstrates this:

ul.CustomMarker { list-style-type : none; }
li.CustomMarker
   {
   background-image    : url('Images/ListItemMarker.svg');
   background-position : left center;
   background-repeat   : no-repeat;
   background-size     : 0.8em auto;

   padding-left        : 1.2em;

   }     
<ul class = 'CustomMarker'>
   <li class = 'CustomMarker'>Lorem</li>
   <li class = 'CustomMarker'>Ipsum</li>
   <li class = 'CustomMarker'>Dolor</li>
</ul> 
  • Lorem
  • Ipsum
  • Dolor

Obviously, the use of class attributes for each list-item element makes the code somewhat verbose, and this is the point where the more-advanced selectors that CSS supports come into their own. That is, the example above could use a ‘descendent selector’, which would obviate all those class attributes, and Appendix C, Advanced Styling & Layout covers​this useful concept in detail.

Borders

To place a border around an element, you use the border property, giving a value for its thickness, colour and style (i.e. dashed, dotted, dot-dashed etc.). In respect of the thickness, you can use only units such as pixels and ems etc. (i.e. not percentages), but only ems are advisable, given the display-technology independence that doing a professional job requires. This means that a border's thickness will scale proportionally with its font size.

As ever, an example serves to demonstrate, so consider the following:

p.BorderedElement
   {
   padding : 0.2em;
   border  : 0.3em solid #606060;
   }     
<p class = 'BorderedElement'>
Lorem ipsum dolor...
</p>

Lorem ipsum ... est laborum.

Developing this example, you can render a non-solid border, as the following demonstrates:

p.DashedBorderedElement
   {
   padding : 0.2em;
   border  : 0.3em dashed #606060;
   }     

Lorem ipsum ... est laborum.

This demonstrates the use of the shorthand border property, but a glance at the box-model diagrams above shows that we have considerable latitude with borders. That is, and to develop the example used so far a little further, you can put a border just to the left and right of an element, rather than all the way round, as the following code shows:

p.LaterallyBorderedElement
   {
   padding      : 0.2em;

   border-left  : 0.3em dotted #606060;
   border-right : 0.3em dotted #606060;

   }

Lorem ipsum dolor...

Bordered elements can also have rounded corners through use of the border-radius property, the simplest example of which is as follows:

p.RoundedBorderedElement
   {
   padding       : 0.2em;

   border        : 0.3em solid #606060;
   border-radius : 1.0em;

   }     

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Using the property in this way causes the user agent to draw a border for each corner as the edge of a quarter-circle of 1em radius. Note that you can use a percentage here, but this will cause the renderer to draw an ellipse (at least in part), which may not be what you want. Consider the next example:

p.PercentageBorderedElement
   {
   padding       : 0.5em;

   border        : 0.3em solid #606060;
   border-radius : 15%;

   }     

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Conversely, this may be exactly what you want. Consider the next example, which exploits this effect:

span.Ellipse
   {
   padding       : 0.5em;

   border        : 0.3em solid #606060;
   border-radius : 50%;

   }          
 <span class = 'Ellipse'>Lorem</span>
 <span class = 'Ellipse'>Ipsum</span>
 <span class = 'Ellipse'>Dolor</span>
Lorem Ipsum Dolor

This suggests some interesting creative possibilities. While the example above applies the definition to spans, it could apply it to <a> elements equally, thus giving the visual impression of buttons that, when touched/clicked would take the user to another part of the content. You could enhance the visual appearance accordingly by the use of element shadows as shown below, and you could give the ‘button legends’ an engraved appearance using the text-shadow property that the previous chapter​explores.

As a follow-up to that, the next example shows another artistic use of the CSS support for borders:

p.ArtisticBorderedElement
   {
   padding       : 0.3em;

   border        : 0.3em solid #606060;
   border-radius : 0.5em 1.5em 0.5em 1.5em;

   }     

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Note that these examples show the use of the shorthand border-radius property, but you can set borders individually using border-top-left-radius, border-top-right-radius etc.

Margins

As the box-model diagrams above indicate, an element's margins lie outside of any padding and border, and allow you to put space between adjacent elements (horizontally or vertically). The following example applies a left margin of 3ems to an <img> element, which offsets the graphic in the third panel to the right, away from the left-hand edge of the display:

img { margin-left : 3em; }
<img src = 'Images/Graphic.svg'>
Lorem Ipsum place-holder graphic

You can also use the margin property to centre a block-type element (meaning that it will not work on non-replaced inline elements) by using the auto value, which the section above on padding introduces, and as the next example demonstrates:

img.Centred
   {
   display : block;

   width   : 8em;
   margin  : 0 auto 0 auto;

   }     
<img class = 'Centered'
     src   = 'Images/Graphic.svg'/>
Lorem Ipsum place-holder graphic

There are four points of note here:

1.

The use of the display property changes the <img> element flow type from inline to block. The technique would fail without this.

2.

The code does not need to set the width of the image explicitly because images have an implicit width. However, if you use the technique to centre elements like paragraphs and lists, you must stipulate a width value even though they are block-flow elements naturally. This is because user agents always attempt to flow text horizontally to fill the lateral space available, and so setting a width explicitly places a limit on this behaviour.

3.

The code uses the shorthand margin property, and so supplies four values, which take the same North, East, South, West ordering explained above.

4.

The actual centring effect occurs because auto causes the renderer to take the width of the enclosing element from which it subtracts the overall width of the element in question (i.e. it includes padding and borders if present), after which it divides the difference by two, thus giving the left and right margins the same value.

Note here that an alternative notation is possible with shorthand properties like margin. That is, if the north and south values you stipulate are the same, and the east and west are equal too, you can provide just two parameters, as the next snippet shows:

margin: 0 auto;

Here the order of the values denotes North/South, East/West. This may seem curious, as the X-axis comes first in mathematics and in other CSS properties, but this ordering reflects the NESW long-hand form.

To develop this idea, and if all margins for a given element should be the same, you can stipulate just a single value, which yields great economy of expression. For example, applying the following:

margin: 3em;

…to a block-flow element will give it a margin all the way around of 3ems in extent. Note, however, that the following:

margin: auto;

…will not centre a block-flow element horizontally and vertically. It will have the same effect as above on the lateral margins, but not the vertical ones, as the concept of ‘vertical centring’ does not apply where inline and block elements flow automatically down the page.

Finally, in this section, it is possible to give a negative value for a given margin – a thoroughly counter-intuitive notion, that is, in fact, entirely legal and useful. A negative value for, say, right-margin will have the effect of pulling any adjacent element in the flow leftwards. That is, it has the opposite of a positive value for right-margin. This is an advanced technique, an example of which you can find in Appendix C, Advanced Styling & Layout, in its consideration​of drop capitals and illuminations.

Element Shadows

To compliment the text-shadow property, CSS defines the box-shadow property, which allows you to cast shadows around an entire element, and which, like the border-radius property, is quite sophisticated. The next example shows it in action:

p.ShadowedElement
   {
   background : #B0B0B0;
   padding    :  0.5em;
   box-shadow :  0 0 0.5em 0.3em #000000;
   }     

Lorem ipsum dolor...

To understand how this works, imagine that the renderer places underneath the element in question a box of the colour specified in the final, fifth value in the rule. If the fourth value is zero, then the box will be the same size as the element; if it is a positive number, it will be larger than the element; if negative, it will be smaller. The renderer also offsets the box horizontally in accord with the first value in the rule, and vertically in accord with the second.

This means that positive values for both will offset it right- and down-wards, and so, in this respect, it operates just like​text-shadow, as the next example shows:

p.SharpShadowedElement
   {
   background : #B0B0B0;
   padding    :  0.5em;
   box-shadow :  0.5em 0.5em 0 0 #000000;
   }     

Lorem ipsum dolor...

In effect, this yields the kind of shadow that physical objects cast on a sunny day. To add blur, you give a positive, third value for the rule, and the next example develops the previous to show this.

p.BlurredShadowedElement
   {
   background : #B0B0B0;
   padding    :  0.5em;
   box-shadow :  0.5em 0.5em 0.7em 0 #000000;
   }     

Lorem ipsum dolor...

In fact, the box-shadow property goes considerably further. Using the keyword ‘inset’ in the rule causes the user agent to render the shadow within the element, and it is also possible to apply multiple shadows to a given element. At the least, this gives an impression of multiple light sources, but skilled use of multiple shadows can yield subtle, sculpted effects. As with the other more-sophisticated features in CSS, you should consult a comprehensive reference if you wish to explore the possibilities here.

Floating

The material above consider matters in the context of the natural or ‘static’ positioning of elements, where the those of inline variety flow across and down the ‘page’, and the box types flow simply downwards. The great majority of e-book producers need no more than this, but the crafts of graphic design and typesetting have long entertained the idea of the sidebar – material that appears as a separate entity at the side of a page, around which text flows. Indeed, this guide makes liberal use of such a device, and you can implement it in your e-books by means of the ‘float’ property.

Consider the following example:

img.LeftFloated
   {
   width        : 10.0em;
   margin-right :  0.3em;

   float        : left;

   }
<div>
   <img class = 'LeftFloated'
        src   = 'Images/Lorem_Ipsum.svg'/>

   <p>Lorem ipsum dolor... </p>

</div>
Lorem Ipsum place-holder graphic

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.

Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

The value ‘left’ for the float property causes any element to which it is applied to ‘seek’ the highest, left-most point within its enclosing element (preferring vertical over lateral placement). Any other elements that follow it in the underlying HTML attempt to flow up around it. This means that the position of a floated element within the HTML is pivotal, as any elements above a floated element in the HTML are unaffected.

Note too the application of a little right-margin. Without this, the flowed text would sit flush with the edge of the image, and the image would be stuck to the top border of the grey panel (which has a small top-margin).

Now consider the next example:

img.RightFloated
   {
   width       : 10.0em;
   margin-left :  0.3em;

   float       : right;

   }     
<div>
   <img class = 'RightFloated'
        src   = 'Images/Lorem_Ipsum.svg'/>

   <p>Lorem ipsum dolor... </p>

</div>
Lorem Ipsum place-holder graphic

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.

Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

This shows the effect of floating an image to the right. To complement the effect of left floating, a right-floated element seeks the highest, right-most point below its previous sibling in the HTML (preferring vertical over lateral placement), and any other elements that follow it in the HTML attempt to flow up around it. In line with the previous example, the CSS code applies a little left-margin to the floated element in order to give a little separation from the body text.

Anything can be floated, and do note that floating an element gives it block-flow status automatically, irrespective of its default flow-type, which causes all paddings and margins to operate fully. In the case of replaced elements like the image used in the examples above, it has no effect on the width of the element, as image elements have width implicitly. However, in the case of textual elements like paragraphs, it causes the user agent to expand the element as far as it can laterally in an attempt to fill its enclosing element completely.

This is normal block-element behaviour, but without intervention, it will stop other elements or text from flowing up around it, and so you must give floated textual elements an explicit width, as the next example demonstrates:

p.Sidebar
   {
   width       : 21.0em;
   padding     :  0 0.3em 0.3em 0.3em;
   border      :  0.2em solid #000000;
   margin-left :  0.3em;

   float       : right;

   }     
<p class = 'Sidebar'>
Ut enim ad...
</p>

<p>Lorem ipsum dolor...</p>

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Given the above, you may think that an image's implicit width precludes setting its width explicitly. In fact, our resolution-independence​mandate means you should always give an ems or percentage value for a given image's width and/or height. This will ensure that it scales in proportion to the text size or the dimensions of a given display device (remember that you need set only one, as the renderer will set the other automatically in order to preserve the aspect ratio).

Finally, in this section, you may think that it is redundant to float elements such as images to the left, because images are inline elements, and so seek naturally the top-most, left-most position possible. This is true, but a textual element like a paragraph will not, by default, attempt to flow up and around a non-floated image that precedes it in the HTML. Only the application of a float rule will cause that.

Float Management

Do be aware that element floating can operate somewhat counter-intuitively; indeed the formal specification is deeply technical and abstruse. For instance, without appropriate intervention, floated elements can cause the effect that the next example demonstrates, where the CSS definition for the sidebar is the same as in the previous section:

div.Container
   {
   padding : 0.3em;
   border  : 0.2em solid #000000;
   }     
<div  id    = 'Container'>
   <p class = 'Sidebar'  >Sit amet, consectetur... </p>

   <p>Lorem ipsum dolor.                           </p>
</div>

Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor.

Here a <div> that possesses a black border acts as a container for an ordinary paragraph, and the right-floating sidebar. The problem here is that the paucity of text in the non-floated paragraph causes the user agent to give that a very short vertical extent, causing it to close-up the containing div vertically too – a consequence in both cases of having block flow. This happens in ignorance of the floated element, which protrudes below the border of the containing div.

You could try giving the containing <div> an explicit height, but there is no guarantee of that working acceptably across all user agents, as, on some it would be too big and on others too small. Happily, the solution is simple: we can use the overflow property again, by applying it to that <div>, with a value of ‘hidden’ as the next example demonstrates:

div.Container
   {
   padding  : 0.3em;
   border   : 0.1em solid #000000;

   overflow : hidden;

   }     

Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor.

Before weighing up an analysis of this, consider the next problem, where, once again, the definition for the sidebar is the same as in the examples above, but where there is no containing <div>, simply an ordinary paragraph that has a background colour:

p.Ordinary
   {
   background-color : #808080;
   padding-left     :  0.3em;
   }     
<p class = 'Sidebar' >Duis aute irure ... laborum  </p>

<p class = 'Ordinary'>Lorem ipsum dolor.             ... consequat</p>

Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Here the text wraps around the sidebar, as you would expect, but this may not be what you want. Moreover, given that the sidebar has no explicit background, and so is transparent, the background to the paragraph extends ‘under’ the sidebar, which may also be undesirable.

To address this, you can apply an overflow rule again with a property of hidden, as the next example shows:

p.Ordinary
   {
   background-color : #808080;
   padding-left     :  0.3em;
   overflow         :  hidden;
   }     

Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Applying an overflow : hidden rule to resolve these two problems – protruding and stacked-over floaters – may seem counter-intuitive. After all, we take the term ‘hidden’ colloquially to mean ‘not visible at all’. In fact, the CSS standard states simply that any legal value for overflow other than ‘visible’ (the default) will yield the solutions demonstrated above, and so you should think of the use of overflow in such contexts as saying ‘there should be no visible overflow’ rather than ‘overflow can happen but should be unseen’.

Moving on to consider further management of the float effect, consider the next example, where, once again, the definition for the sidebar is the same as used in the examples above:

p.Ordinary
   {
   padding-left : 0.3em;
   }     

Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Here the first and second ordinary paragraphs flow up and to the left of the sidebar. However, you may not wish the user agent to render that second paragraph in ignorance of the sidebar. CSS provides for this in the form of the ‘clear’ property, which can take one of four values: ‘left’, ‘right’, ‘both’ and ‘none’.

Applying this with a value of right to the second paragraph in the last example yields the following:

p.Ordinary { padding-left : 0.3em; }

p.RightClearing
   {
   padding-left : 0.3em;
   clear        : right;
   }     
<p class = 'Sidebar'>
Excepteur sint occaecat ... id est laborum.
</p>

<p class = 'Ordinary'>
Lorem ipsum dolor ... dolore magna aliqua.
</p>

<p class = 'RightClearing'>
Ut enim ad ... ea commodo consequat.
</p>

Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

That is, applying clear to an element tells it to avoid being caught up in any floating that happens before it in the HTML.

With these points aside, note that the Kindle Touch, the Kindle Previewer development tool (in both e-ink and Fire mode) and Kindle for PCs exhibit a rather serious bug currently, which may manifest on other variants of the Kindle product range. Consider the following example:

img.RightFloated
   {
   width       : 8em;
   margin-left : 0.3em;
   float       : right;
   }     
<div>
   <img class = 'RightFloated'
        src   = 'Images/Lorem_Ipsum.svg'/>

   <img class = 'RightFloated'
        src   = 'Images/Lorem_Ipsum.svg'/>

   <p>Lorem ipsum dolor ... id est laborum.</p>

</div>

This code should generate the following on a given e-reader:

Lorem Ipsum place-holder graphic Lorem Ipsum place-holder graphic

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

However, if you used that code in your book, Kindle users might see the second graphic placed below the first, as the next example demonstrates:

Lorem Ipsum place-holder graphic
Lorem Ipsum place-holder graphic

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

This behaviour is incorrect, and it is an out-and-out bug in the renderer in question. Happily, it need not affect your design ambitions, as there is a work-around, which the example before last uses in order to give a reliable demonstration of the defect.

The solution is to use a table to hold the elements that you wish to float, and to float that element to the right rather than the elements it carries. The irony here is that the web design and development community take a dim view of table-based layout, as Chapter Six, Composition, explains.​Indeed, Amazon recommends also that you avoid that approach, which is fine advice, given that a defect in their software forces its use.

The next example gives the code for emulating the correct behaviour when floating multiple elements (which is the code that implements the previous example):

table
   {
   margin-left : 0.3em;
   float       : right;
   }

img { width : 8em; }
<table id = 'Element_Subsumption_0'>
   <tr>
      <td><img src = 'Images/00_Lorem_Ipsum.svg'/></td>
      <td><img src = 'Images/00_Lorem_Ipsum.svg'/></td>
   </tr>
</table>

A final point in this section: do not think that you could exploit the float bug to get the erroneous effect it generates on purpose. This would rely on the presence of the defect in a given user agent, which could never be guaranteed. If you do wish to float multiple elements as a columnar group, there is an entirely moral and legal method that does not use tables, and which Chapter Six, Composition, covers​in its discussion of positioning techniques.

Page Breaks

The concept of page breaks in web sites does not apply, as browsers present content collectively as a scrollable object. However, CSS defines a set of properties that cater for print media, where control of the points at which the flow of content breaks before re-starting on the next page is of critical importance.

By definition, e-books are not a manifestation of print, but e-readers implement the page metaphor anyway because they present content only as a linear set of segments, through which one progresses one segment at a time. (Note that some e-readers support a browser-like scrolling mode, but they are not in the majority.) The only differences between that and print are that e-reader users may change the size of the text, and may switch between portrait and landscape mode, both of which change the amount of content that can be made available in a given segment. That is to say, pagination in print media is static, whereas e-readers implement dynamic pagination.

Static or dynamic, however, self-respecting publishers avoid things like ‘widows’ and ‘orphans’. The CSS standard defines a widow as trailing lines of textual content, where the containing element begins on the previous page. Conversely, it defines an orphan as leading lines of textual content that occur at the bottom of a page, where the remainder of the containing element to which they belong continues on the next page (although do note that, in typography as a whole, some people define these terms the other way round).

Definitions aside, and in practice, such things break the flow of content, thus impinging on the reading experience, and thus they look sloppy and unprofessional. Moreover, in technical books, the ideal is that content elements such as lists, tables and code listings should take up no more than a single page, and should not span a page boundary.

This is vital in programming books, where readability and hence comprehension pivot on the proper presentation of code, yet print publishers are often sorely remiss in this respect. It is common to see lines of code in programming books that wrap around at the right-hand side of the page (disastrous for readability), and entire listings that span two, three or even more pages. At best, having to flip back and forth while trying to parse someone else's code is frustrating; at worst, it prompts you to give up.

It is clear therefore that, in principle, e-book publishers should avail themselves of the pagination-related properties that CSS defines, and that e-readers should support such features fully too. Sadly, in respect of the latter, reality falls far short of the ideal.

CSS defines a number of properties that cater for paginated media, and these are:

These all apply to block-flow elements only, and the page-break- properties take keyword values, while widows and orphans both require a positive integer. For widows, that value stipulates the minimum number of lines that the user agent should allow to spill over from a previous page. That is, a value of five applied to all <p> elements should mean that the user agent never splits a paragraph at the end of a page such that four or fewer lines spill over to the next page. Conversely, a value of five for the orphans property, when applied to all <p> elements, should mean that the user agent never splits end-page paragraphs such that the first four or fewer lines of text begin at the end of the page, while the rest spill over to the next.

Obviously, you could go further than applying these solely to paragraphs, as one truly ugly phenomenon is the presence of a section title at the bottom of a page while the body of the section that it introduces continues on the next page. To resolve this problem, you could wrap each title element and its first paragraph in a <div> to which you give a suitable class name, and to which you apply the orphans property with a value of zero.

This is a great idea, and, on at least one flavour of Kindle, the Touch, it does not work…

Beyond that, the page-break-inside property would seem to be a perfect fit for the problem of code listings spanning multiple pages. Here you could give each code-containing element a suitable class name and then apply page-break-inside to elements with that class name, giving it a value of ‘avoid’ (the only other possible value being ‘auto’ which means, essentially, ‘let the user agent decide’). This too is a great idea that does not work.

Aside from those properties, page-break-after does actually work on the Kindle, and Amazon's documentation recommends its use in pagination control. In principle, you can use this to preclude orphaned section headings by wrapping each section in a <div>, and applying the page-break-after property with a value of ‘always’ to all such divs. This will ensure that each section always starts on a new page (i.e. with the section heading at the top of the display), but it comes at the unacceptable cost of many previous sections ending prematurely on the previous page, leaving an expanse of blank-screen that suggests the reader has reached the end of the chapter.

One day, one hopes, the powers-that-be will get their corporate-programming-act together and fix these unnecessary software deficiencies for which well-understood, algorithmic solutions certainly exist. In the meantime, the best thing that e-book producers can do is to include pagination-control definitions in a given book's body of CSS code, as a matter of course, ready for when that day comes.