demosthenes.info

I’m Dudley Storey, the author of Pro CSS3 Animation. This is my blog, where I talk about web design and development with , and . To receive more information, including news, updates, and tips, you should follow me on Twitter.

featured articles

popular favourites

CSS and Images: The Float Quirk and Clear Solution

While the float quirk issue is by no means solely confined to images, it is most commonly associated with them, and so is addressed here.

Float Quirk Example ScreenshotThe “float quirk” problem typically occurs when you have images that are both floated on the same side of the page in close proximity to each other. In our example, we will have a class that describes a similar format for a set of images. (Remember, class styles are for elements that occur multiple times on the same page and share the same properties, but the appearance used is not applied to the majority of the uses of the element on the page).

For example, a style in an embedded or linked style sheet:

  1. img.theremin { height: 370px; width: 300px; float: right; margin-left: 1em; }

And for our code:

  1. <p>The theremin is one of the only truly new musical instruments
  2. created in the 20th century. Other instruments, such as the electric guitar
  3. and electronic synthesizer, were derived from existing classical forms, but the
  4. theremin, invented by Russian professor Léon Theremin, is completely novel.
  5. <img src=”images/theremin-performer.jpg” class=”theremin” alt=”Theremin
  6. performer” title=“Theremin performer” /></p>
  7. <p>It remains the only musical instrument that is not physically touched to
  8. produce a tone.Instead, musical pitches are generated by the musician’s
  9. interaction with two separate electric fields – one for frequency,
  10. the other for amplitude. A theremin performance is as much physical
  11. as it is musical, and
  12. <a href=”http://www.ted.com/talks/pamelia_kurstin_plays_the_theremin.html”>
  13. watching one</a> can be a mesmerizing experience.</p>
  14. <p>Sounds produced by the theremin are continuous and glissading, creating
  15. an “eerie” or haunting tone. The instrument was used to great effect in movies
  16. such as <cite>The Day The Earth Stood Still</cite>,
  17. <img src=”images/gort.jpg” class=”theremin” alt=”Gort, from The Day The Earth
  18. Stood Still” title=”Gort, from The Day The Earth Stood Still” />
  19. and in the Beach Boy’s <cite>“Good Vibrations”</cite>.</p>

Float Quirk Solution ScreenshotThe result will typically look something like the screenshot above. As the width of the browser window narrows, the second image will be forced down, until the point at which it “pops” under the first, to produce the effect that we were likely after in the first place.

So what is happening? Very simply, CSS is doing exactly what you tell it. float: right applied to an element means “float to the right of any content that comes after me”. For the first image, that content includes the second image, which follows it.

In order to fix this problem, we need to modify the CSS for the second image. The existing class is still true for both images, so ideally we could add to it:

  1. img.theremin { height: 370px; width: 300px; float: right; margin-left: 1em;
  2. clear: right; }

(If the images were different sizes and had separate inline styles we would only need to add clear: right; to the the second image. For this example, adding clear to the class is a little redundant, as the first image won't be affected, but it is a more efficient approach than adding a separate inline style to the second image.)

clear is a deceptively simple property that can take one of five values: left, right, both, inherit and none. It essentially means the following: “do not allow anything to float to this side of me”. In our case, our images are floated right; we don’t want anything to be to the right of those images, and clear: right takes care of that.

We would also typically add a margin-bottom property to separate the images visually:

  1. img.theremin { height: 370px; width: 300px; float: right; clear: right;
  2. margin: 0 0 2em 1em;}

CSS Background Images

CSS can also be used to place images in the background of any element. The property to do so is background-image.

  1. body { background-image: url(‘images/gradient.gif’); }

We cannot use src for this – that is an HTML attribute value, not a CSS property, and reserved for use with the <img /> tag. Nor can we use href or a link tag for similar reasons. But once you are past the url prefix, the parentheses and the single quotes (or double quotes, or no quotes at all – either may be used, so long as they are used consistently), the path to the image in the background-image property value is the same as if you were inserting an image directly on a page.

I wish to emphasise that an image can be placed in the background of any element. That being said, body is the most commonly used element for this technique, so we will continue with in our initial example.

We should also note that images that are to be used for backgrounds should be processed through to lower opacity, reduce file size and to create seamless integration between repetitions of the image.

By default an image used as a background image will tesselate both horizontally and vertically through the space used by theelement. If we want to change that, we alter the value of the background-repeat property:

  1. body { background-image: url(‘images/gradient.gif’);
  2. background-repeat: no-repeat; }

background-repeat can also takes values of repeat-x (to tile horizontally) and repeat-y (to create vertical tiling of the background image).

You can also position the background image in reference to your element. Note that the numerical origin of this position is always the topleft corner of the element’s box.

  1. background-position: 20em 10px;

The position values are always horizontal position followed by vertical position, separated by a space, unless the single keyword center is used (note the spelling). For the example above, our background-image would be 20em from the left side of the body and 10px from the top. Numerical position may be measured in any of the CSS units I haveintroduced you to, including mixtures of units, as shown in the example above, and may include negative values.

background-position may also take keyword values: top, center and bottom for the vertical component, and left, center and right for the horizontal. background-position is left top by default. If you wish to have a background image in the center of the element, you may just use:

  1. background-position: center;

CSS and Images: Simple Roll-over Image Gallery

If you have been reading these articles in order, this lesson gets a little ahead of the concepts introduced so far, and uses properties (primarily ) that have not yet been thoroughly explained, I find it a useful example to wrap up a course / semester.

Simple CSS Gallery ScreenshotThere are many, many different possible methods to create image galleries. Many people use complex , when all is required, in most cases, is some simple combined with semantic markup.

What I’m about to show you is a synthesis of several techniques combined with a few of my personal additions. To complete this exercise, you’ll need three thumbnail photographic images, ideally all the same size, and three matching large versions of those same images. For clarity, save the large versions of the images as subject.jpg and the small versions as thumb_subject.jpg.

Once we have our content, the question is what markup makes the most semantic sense for what we are trying to express? What we desire to create is a set of thumbnail images that, when interacted with, reveal larger versions of themselves with an explanation of their context and meaning. Once again, the incredibly useful (and relatively unknown / unappreciated) definition list comes to our aid: we are, at heart, talking about a series of terms (which could be words, images, links, or anything else) that are expanded upon with a definition declaration.

So our markup is fairly straightforward:

  1. <dl id=gallery>
  2. <dt><img src=thumb_maple.jpg alt="Maple tree">
  3. <dd><img src=maple.jpg alt="Maple tree">
  4. <dt><img src=thumb_oak.jpg alt="An oak tree">
  5. <dd><img src=oak.jpg alt="Oak">
  6. <dt><img src=thumb_sequoia.jpg alt="Fallen sequoia">
  7. <dd><img src=sequoia.jpg alt="Fallen sequoia">
  8. </dl>

(Note that for the purpose of this exercise I am assuming that every thumbnail is the same size, so I could put their width and height as part of a dl#gallery dt img { } declaration in a style sheet if I wanted to. If the thumbnails were all different sizes, you would put the width and height as separate inline styles for each image, as you normally would for the large images. I am also assuming that all images are placed in an images folder next to this HTML page.)

On viewing the web page in our browser we’re immediately confronted with several problems. The first is that our large images are visible, and we only want them to appear when the user hovers over a thumbnail image.

There are many CSS properties that can be used to make elements on a web page “disappear”: display, opacity, pushing things off the screen with margin or position, and more. We will use visibility:

  1. dl#gallery dd { visibility: hidden; }

That hides our large images, but preserves the space they take on-screen. We’ll get around this by positioning the dd elements absolutely:

  1. dl#gallery dd { visibility: hidden; position: absolute; }

Using absolute positioning on elements takes them out of the “flow” of the document: the web page acts like the definition declarations are no longer there, and collapses the remaining structure of our document. (The <dd> elements and the images they contain are still present, of course, simply hidden by our visibility: hidden rule. You could see where the images are by removing or commenting out that part of the style declaration.)

position: absolute is very useful, but very dangerous – if not used carefully, it leads to positioning every element on the page absolutely, due to designer’s misplaced desire for “pixel-perfect layout” and the aforementioned collapse due to the removal of absolutely positioned elements from the flow of the document. position: absolute should, as a general rule, be avoided unless it is absolutely required – and when used, you should know why you are using it, rather than “it just works this way”.

In this case, position: absolute is used for an eminently logical reason: we want all of our large images to appear in the same location. Right now, they are not (again, turn off visibility: hidden temporarily to see where they are). In addition, we want the position of the large images to be measured in respect to their relation to the definition list as a whole. This is a two-step process. First, some CSS for the definition list itself:

  1. dl#gallery { position: relative; }

The reason for this line will be discussed in future entries – for now, the rule is:

Absolutely positioned elements position themselves against the origin of the body (i.e. the top left corner of the web page), unless they are within another absolutely positioned or relatively positioned element.

In essence, we’ve told the absolutely positioned <dd> elements to measure their position against the definition list, rather than the body. We can see this by once more temporarily commenting out the visibility of the <dd> elements and adding more CSS to the style declaration:

  1. dl#gallery dd { /* visibility: hidden; */ position: absolute; top: 20px;
  2. left: 200px; }

Naturally the numbers for left and top are guesses; you should feel free to adjust them to suit your particular design before turning visibility: hidden back on.

The penultimate step is to make the <dd> elements appear only when we are hovering over the thumbnail images. Looking at our markup, we can see that each <dd> element is immediately preceded by a <dt>. We also recall that :hover can be applied to any element, not . Ergo, the solution is a combination:

  1. dl#gallery dt:hover + dd { visibility: visible; }

This CSS solution is a good one, with just one remaining problem: you can make the large images visible by moving your mouse to the right of the thumbnail images, where the <dt> is still active. This is due to the fact that <dt> is a block tag, and therefore stretches all the way across the page by default. But if it’s a block tag, we can apply width to it. Assuming that your thumbnail images are all 75 pixels wide:

  1. dl#gallery dt { width: 75px; }

The complete CSS code:

  1. dl#gallery { position: relative; }
  2. dl#gallery dt { width: 75px; }
  3. dl#gallery dd { visibility: hidden; position: absolute; top: 20px; left: 200px; }
  4. dl#gallery dt:hover + dd { visibility: visible; }
Lossy compression example

Images: Lossy vs Lossless Compression

Modern web browsers accept four image formats by default: JPEG, GIF, PNG and SVG. But before talking about formats, let’s introduce two extremely important terms: lossless and lossy compression.

Almost all images are compressed in some way. That is, the raw binary data that makes up the individual pixels and their color is packaged up and rearranged to achieve the smallest file size possible for any particular format. There are many different methods of data compression, but they all come down to one simple question: whether the bits are physically altered.

Lossless compression does not change bits. It rearranges them, and tries to pack them into a smaller space - think of different arrangements of boxes in a moving van in an attempt to fit more inside - but does not physically change them. You obviously want a lossless compression scheme in situations for which fidelity to the original data is paramount. .zip is a ubiquitous compression scheme: bits go in, information is re-arranged and compressed, but the same bits come out after you uncompress the .zip. (You don't want the “Z’s” in a compressed Microsoft Word document to be changed to “k’s” just because it would make the file smaller.)

There are many lossless image compression formats: TIF, TGA, BMP, RAW, PNG, SVG and PSD among them. Arguably, even GIF is a lossess format. Assuming that you are feeding them the best information possible, all of those formats will preserve data completely, without loss or change. The easiest compression scheme is run-length encoding: if there are several pixels of the exact same color one after the other in a horizontal line, rather than counting them separately, GIF makes a shortcut code for them (say “five red pixels”, rather than counting “one red pixel, another red pixel…” and so on).

The major drawback to a lossless compression scheme (with the exception of SVG, which is predominantly a vector format) is file size. No matter how clever the algorithm, the data must be completely preserved. But what if we could change some of that data - squish it, alter it, or even throw it out - in such a way that the end user is unlikely to spot any changes?

This can’t be done with Word documents… but pixels are very small. If we can change some of them to be more like their neighboring pixels, we would increase the number of shortcuts we could take in describing the image, which in turn would reduce its file size. And that’s exactly what lossy compression does. There are a few lossy compression schemes for images; JPEG is the most well-known.

Lossy compression gives significant advantages in terms of file size. However, it comes with one major caveat: the changes made to the image to achieve this compression can't be undone. That is, the original information is lost, and can't be retrieved. (And no amount of digital wizardry can recover it - despite what the movies and television tell you).

Images for the Web: Production Workflow

The creation of web content is all too often a constant cycle of revision and tweaking. Avoiding process iterations saves time and money while lowering frustration: sticking to a reliable, organized production workflow is key to the efficient creation of web sites.

However they are generated – from photographs, directly in or Inkscape, or by scanning – the original images used to create our work must, as much as possible, be retained in a lossless format, and be as high-resolution as possible. These originals will be drawn on to create the final, web-ready images; for this reason, I create a standard folder structure for every site:

Site assets folder heirarchy screenshot
Typical site folder heirarchy organisation

The assets folder contains all the material used by my site: , , etc, each inside an appropriate sub-folder. The originals folder contains source material: my RAW files from the digital camera during a product shoot, for example. The originals folder is not part of the site per se, and is not uploaded to the remote, “live” site.

Step 1

Create your source files in lossless format, in as high a resolution as possible, and store them in the originals folder.

Step 2

Export two versions of each picture into the images folder:

  • A full scale version for high resolution devices, with "@2x" appended to the filename. For example, [email protected]

  • A copy of the image reduced by 50%, to its “normal” size, and exported without an added suffix (e.g. milton-friedman.jpg )

Vector-based art, such as corporate logos, maps, and diagrams, are typically exported in format, and do not have a resolution. They may be saved in a seperate svg folder.

Web developers in major cities tend to have broadband, high-speed Internet access. Step outside the major cities, and slow connection speeds become much more common; international distances drag connection speed to a crawl. Rural experience of the web is very different from the cities. Every web site, whatever its intended audience, is international in scope, and we should try to keep our sites accessible to as many people as possible by keeping file sizes low.

Our goal is to make the total file size of any page - code, content, scripts, CSS, and images, all added together - less than 100K in size. A 100K page will download in less than 10 - 12 seconds, even over a slow connection, and eight seconds happens to be the attention span of the average web user.

This 100K limit is a goal, not a hard-and-fast rule for every page of every site. There will be reasons for going above 100K, but the motives for doing so must be judged carefully. The primary contributor to page size is usually images, so it behooves us to try to make them as small as possible, via the following methods:

  1. Reduce each image to its smallest practical width and height.
  2. Crop out extraneous details: ruthlessly remove pixels you don't need.
  3. Remove any framing effects around any images (picture frames can be created far more effectively in CSS).
  4. Remember that the most common screen resolution on the web is currently 1200 × 800 pixels, and that the actual size of the browser window is significantly under that, so anything over those dimensions is wasteful.

Step 3

Choose the appropriate image format, and optimise the image's settings for that format.

Bitmap Images for the Web: Formats and Optimisation Options

GIF (Graphics Interchange Format)

NASA
The NASA logo, a good example of the correct use of the GIF format
Mnemonic:

GIF is for Graphics.”

Color depth:

8-bit (256 color)

Used for:

Graphical art (any image that consists mostly of flat areas or lines of contiguous color: most logos, diagrams, drawings, maps, cartoons, arrows, etc). Text that must be turned into bitmap images is usually saved in GIF format. may be considered as an alternative format in some circumstances.

Compression:

Uses LZW compression algorithm in run-length encoding. Lossless, assuming that colors in the original image are the same as the target palette of the GIF.

Optimal settings:
  • Optimal GIF SettingsMinimise the number of colors (you can type in and experiment with the number of colors used; it does not have to be what or any other image editor suggests).

  • Try using the “Restrictive” palette first. “Perceptual”, “adaptive”, “selective” or “greyscale” may also be options.
  • Try to keep “Web Snap” at or near 100%.
  • Try to keep “Dither” off.
  • Do not attach metadata unless you are actively using it as a means of captioning the image with PHP or part of a sitemap
  • “Transparency” may or may not reduce file size. Experiment with removing the background to the image and turning “transparency” on and off.
  • “Matte” only matters if “transparency” is on. If it is, “matte” should be set to the predominant background color the image will be set against.
  • Finally, experiment with interlacing. If turning it on reduces file size, leave it on.
Transparency:

One color only may be specified as transparent. (Tends to produce “halo” effects when used against colors that are different from its assumed background color.)

Other features:

Can be animated.

JPEG (Joint Photographers Experts Group)

Christine Adams
A photograph of Christine Adams, saved as a JPEG
Mnemonic:

“JPEG is for Photographs.”

Color depth:

24-bit (16,777,216 colors)

Used for:

Photographs.

Compression:

Uses lossy compression. Technically: 8 × 8 pixel blocks are transformed via a discrete cosine function into a quantized matrix of coefficients. Less technically: JPEGs can appear “blocky” at higher compression ratios.

Optimal settings:
  • Optimal JPEG SettingsIgnore “Low”, “Medium”, “High” pre-settings.
  • Start the “quality” slider as low as possible. 20 is a good start, but you may be able to go as low as 10 to 15 in some cases.
  • Don't think of the slider as “quality”, but as compression, with high compression to the left, low to the right.
  • Judge the visual quality of the image at normal resolution (i.e. no zoom). If the quality is acceptable, leave the slider position where it is (or even move it down a notch). Otherwise, work the slider up in small increments (steps of 5 or 10) until the quality becomes acceptable.
  • Do not attach metadata unless you are actively using it as a means of captioning the image with PHP or part of a sitemap.
  • Ensure that you convert the image to sRGB.
  • Turn “progressive” on for images greater than 10K in size: it will usually be smaller a smaller file size, and the image will feel like “loads faster” while looking better on high-density displays such as Retina-based Apple devices.
  • “Blur” is not usually required, but may be useful if the image was already blurred to begin with. Higher levels of blur will allow the JPEG compression algorithm to further decrease file size.

PNG (Portable Network Graphic)

Google Maps icon
Google Maps icon, a good example of the PNG format
Mnemonic:

GIF and JPEG met, married, and had a baby named PNG

Color depth:

8, 16, 24, or 32-bit

Used for:

Lossless compression of graphics or photographs. Images for which an alpha mask is required. Can, in theory, be animated, via the APNG format. Often a smaller file size than GIF, and therefore often a better alternative ( is another possibility).

Compression:

Uses a lossless compression algorithm. Tends therefore to have large file sizes.

Optimal settings:

8-bit PNGs follow the optimization guidelines for GIFs. 24-bit PNGs follow the applicable optimization values for JPEGs.

Transparency:

8-bit alpha mask (256 levels of grey, the same as PhotoShop). Not supported well by Internet Explorer before IE8.

Once you have stepped through the workflow we have discussed: creating the original image in as high a resolution and color depth as possible; saved it in an originals folder in your site; reducing the image size, eliminating excess pixels; and saving the image as a GIF, JPEG or PNG, with optimized settings, you are ready to add the final web-ready image to your page. (You don’t need PhotoShop to optimize images: online resources such as Kraken can also do a good job of compressing your files.)

Edit Image Metadata With PhotoShop

Auto-captioned image with ITPC metadataMost images contain metadata embedded in the bitmap file. In digital cameras and some other media, this data is in EXIF format. (The acronym is a little bit of misnomer: EXIF is also used in some audio formats).

EXIF is intended to be a “write once, read many times” record: only information germane to the original image at the moment it is made, such as time, place, focal length settings and ISO, are meant to be embedded.  Many applications, including , have the ability to read and re-write EXIF, as does . However, there are a few issues with using EXIF as a source of image captioning for web pages:

  1. Different manufacturers record EXIF data inconsistently in digital cameras; there is, as yet, no one standard.

  2. EXIF data is often stripped or modified as an image moves through a workflow (for example, in PhotoShop) or web services: Facebook deletes EXIF information from images, in part to avoid privacy concerns. (Not everyone wants their home to be located from their posted photographs: many cameras, including those in mobile phones, embed the current GPS coordinates in EXIF data.)

  3. It is relatively rare for designers to put raw images with fully preserved EXIF data on web pages.

  4. EXIF data is only supported in JPEG, TIFF, BMP, and a few other formats; embedding in GIF and PNG is not officially supported.

Instead, I’d suggest using IPTC data as a source of captioning information. The format is richer and more diverse than EXIF, while eliminating all the drawbacks above, except for the last: PHP doesn’t support reading IPTC from PNG or GIF files. (In order to do that, I would recommend RDF… but as an XML standard, RDF is somewhat harder to explain and use… so I will leave that for another time.)

PhotoShop CS5 image File Info ScreenFirst, we need to make sure our images are correctly tagged with ITPC data. If our portfolio consists of just a few images (or if you have the ability to add metadata while editing the image) I would recommend using Adobe PhotoShop or Bridge to add the correct information. In PhotoShop, the metadata editor is found under File / File Info…  (For this example, I’ll use a Creative Commons licensed photographs by René González.)

As you can see, there are many options for adding metadata to an image (the adventurous will spot our old friend Dublin Core as one possibility). For right now, we’re only interested in the areas most easily accessed by PHP: the ITPC tab, most particularly the slots for creation date, location, and content of the image.

PhotoShop Save For Web with Metadata onWith the data added, save your image as usual, with the alteration that you must turn on the option for metadata: either the All Except Camera Info or All option.

web developer guide

featured comment

by Aisling Brock in New Business Card Design

what i'm reading

A Feast for Crows: A Song of Ice and Fire: Book Four
A Feast for Crows: A Song of Ice and Fire: Book Four

what i'm watching

Prometheus: Collector's Edition (Bilingual) [Blu-ray 3D + Blu-ray + DVD + Digital Copy]
Prometheus: Collector's Edition (Bilingual) [Blu-ray 3D + Blu-ray + DVD + Digital Copy]

what i'm playing

Borderlands
Borderlands

what i'm hearing

Planets
Planets

blogs

podcasts

no ads ever

This blog is free of advertising, and always will be.

creative commons licensed

The content of this blog is free to use in whatever way you wish under the Creative Commons license.