Printing The Web

Printable Websites - some books

While it is possible to consume nearly all means of content on your smartphone or tablet it seems like the dream of a paperless office comes true for a lot of web developers.

But digital natives are not the only ones who are on the web. There are still some people that like to print web sites on paper. Once you are aware of that you might want to include a dedicated print stylesheet into web sites you build. Here is some advice on what you can do to get the best out of your page.

Disclaimer: This article was first published in the German Screen Guide Magazine #15 (September to December 2012, pages 77 to 79). This article features more content and better research.

The basics of a print style sheet should already be well known by most web developers. There are two possible ways to include CSS for print:

  • a separate file included in the HTML that carries all CSS for print media
    <link rel="stylesheet" media="print" href="css/print.css">

  • a special media query which targets print mode and is integrated into your regular stylesheet
    @media print { … }

The decision which way to go is pretty obvious: We do not want to have another request to the server for an extra style sheet and thus will embed the styles using a media query. With the help of preprocessors such as LESS or Sass and build systems it is easily possible to put these styles into separate files and concatenate them when needed for production.

Remove Clutter

In general focusing on the main content of a web page is very important when it comes to print style sheets. Remove unnecessary page elements such as navigation and the footer using display: none;. However you might not want to remove a logo that identifies your website from the printed version. (Maybe you have an optimized monochrome version that looks better when printing black and white – you can include this as a background-image. This can be overwritten via the user’s configuration though.)

Think about readable fonts and appropriate font sizes – in print you usually want to have a size not bigger than 12px for your body copy, but on screen 16px is totally appropriate. Furthermore it is important to print mostly dark colors on light background. It might be the best solution to use black as the default text color.
This is also more economical than printing other colors.

When in doubt, print the page while developing it to get a better feeling for the font setup.

Improve The Content

There are a couple of techniques to add more value to the content of a page. One is to add the URL of a link directly after the link text. Don’t do that for links that link to sections of your page or have JavaScript handlers, because it will not carry any meaning for the uninformed reader:

a[href]:after {
    content: " (" attr(href) ")";
}
 
a[href^="#"]:after,
a[href^="javascript"]:after {
    content: "";
}

This is also useful for the abbr element (for abbreviations) and its title attribute. (The same rule technically appies to acronym – thanks to Adrian Roselli).

abbr[title]:after {
    content: " (" attr(title) ")";
}

You can find a more detailed post about this technique here.

Edit: As Tim suggests in the comments it might be necessary to use word-wrap: break-word; on these elements as especially links can become pretty long and thus break you layout.

Remember that browsers normally display a header and footer line with some information about your site such as the URL it was printed from or the date. The user might have an option to remove those lines so you may want to include some link or a breadcrumb in the printed page so the reader can easily check back on the web if needed. Other methods outline embedding a QR code on the printed page. Adrian Roselli describes this method further.

In general most style sheets might be done with these few considerations. But there are some more helpers and CSS rules that can come in handy in certain cases.

A few weeks ago there was an interesing article at Smashing Magazine which has some more useful tips for dealing with links, images and so on. Check it out if needed.

Structuring The Page

Let’s dig a bit deeper.

The at-rule @page allows you to specify the structure of the page. Here is an example of how you can configure the margin of the page:

@page {
    margin: 2cm 1.5cm;
}

Furthermore it is possible to define styles via pseudo-classes. With :first for instance you target only the first page of a document, :left and :right target all even/odd pages (this depends on the direction of writing in a language). This can help you if you want to print a manuscript or magazine for example.

It is possible to name a property and apply it to differnet elements. This comes in handy if you want to print tables in landscape mode:

@page tables {
    size: landscape;
}
 
table {
    page: tables;
}

This is far more experimental and can not be used reliable. Check out this test case. Please see the specification for a more detailed explanation.

More information about the @page rule can be found at the Mozilla Developer Network.

With size you can specify the size of the sheet you want to print your document on. The initial value is auto which sets the width to a DIN A4 sheet with a size of 210 × 297 millimeters. You can target an expected DIN A5 sheet this way:

@page {
    size: 148mm 210mm;
}

Even though this is possibile you should let the printer defaults handle the size of the sheet, especially since DIN A4 is not used in the US for example.

Side note: Please be aware that it is still not possible to cut a sheet via CSS, thus it is only an expected size. I know this sucks! 3D printers might save us soon.

Page-Breaks

Both properties page-break-before and page-break-after specify when a page break occurs and when you do not want it to happen. For instance you most likely want to avoid page breaks after a headline:

h2 {
    page-break-after: avoid;
}

Possible values of page-break-before and page-break-after are:

  • auto – default value, no specified behavior
  • always – invokes a page-break
  • avoid – tries to avoid a page-break
  • left/right – single or double page-break to get the element to start on either the left of the right page, interesting when you want to print brochures or books.

Furthermore, there is the property page-break-inside which behaves similarly but only supports the values auto and avoid. While avoid specifies that there sould be no page-break within the element and auto does not specify a specific behavior.

Experimental Properties

The next few features are still in development or only supported by single browsers. Some of them are part of the (not really) new CSS Paged Media Specification.

Print What You See On Screen

The property -webkit-print-color-adjust: exact; only works in WebKit browsers (namely Chrome and Safari) and enables you to print a page exactly as it is displayed on screen. Mostly this means that you can print CSS backgrounds. But be careful, there is a bug when it comes to gradients: Gradients are not printed at all. Also it is not possible to define the property on the body element (Whaaaat? :/).

You need to use this property if you want to print a b/w-optimized logo as outlined earlier and you don’t want to include an image in the markup.

Other browsers such as Firefox allow users to specify whether they want to print background images and colors via an option in the print dialogue.

Widows And Orphans

To prevent single lines of text to be at the end of one page you can adjust how many lines have to be tied together with orphans. p { orphans: 3; } for instance requires at least three consecutive lines in a paragraph on the end of a page.

In contrast – only one line at the beginning of a new page – widows helps you out. So with article { widows: 2; } you will get at least two lines of text for an article on a new page.

Crop Marks And Page Bleed

Sometimes you need specific declarations on how to cut a sheet of paper. With marks it is possible to set marks via the values crop and cross while crop adds crop marks and cross adds fiducial marks.

If this property is set you can specify how far the printable area spreads out of the area defined by the aforementioned marks by using the property bleed while using one of the units defined in the values and units specification.

This property is part of the CSS Generated Content for Paged Media Module which is basically to really recognized by the browser vendors.

Boxes On Page-Break

The property box-decoration-break specifies how for example background, margin or border behave when the page breaks. There are two possible values for this property (also see the picture):

  • slice – default value, literally “slices” the box into two parts
  • clone – dupicates the styles that are applied to a box on each page

This is currently supported by Opera with the Presto Engine and will shortly be availabe in Google Chrome. Lennart Schoors wrote about this property a while ago on his blog Bricss.

In Firefox there is -moz-background-inline-policy which enables you to treat background images how you want to. But this is clearly only a partial implementation of box-decoration-break.

More On Browser Support

While the at-rule @page is supported by all major browsers except Internet Explorer 7 and was just implemented by Firefox a few months ago. Most other properties are far more complex:

  • You should use page-break-before and page-break-after only with its value always since the other values are not supported widely
  • page-break-inside is not supported in Internet Explorer 7.

You have to be aware that nearly all experimental properies lack support in most browsers and are only implemented by one major engine. For example orphans and widows are only supported in Internet Explorer since version 8 and Opera – which will soon be history as of their change to WebKit. marks and bleed is not implemented in any browser so far.

What Is Missing?

There are certain drawbacks when it comes to styling for print: Up until now there is no good possibility to define header and footer lines for your pages which would be very helpful for paginated printing. You can use pseudo elements of the body element which enables you to set a header and a footer on the first and last page. But this is by far not what is needed. You will run into this problem when you try to print tables: it is simply not possible without duplicate markup to print the thead of the table on each page (while repeating markup is not a real solution as you don’t know where a page breaks).

The funny thing is the specification of thead and tfoot states that it might be useful to repeat the elements on each page. Sadly no browser vendor implemented this yet.

But it is possible to create a solution for that. It could be a nice thing to implement JavaScript events that get invoked right before a page is printed. But as Simon Sapin states this is not really possible due to the mechanisms how browsers layout a page:

Page breaks happen during layout, much too late to do DOM manipulation (which invalidates and restarts layout). It’s really up to the layout engine to do this.

Also more properties for @page could be helpful to generate header and footer for each page.

Luckily the Paged Media Specification tries to tackle this problem. This specification has just become a Working Draft.

Here is an example on how you can implement a footer with the page count on every page:

@page {
    counter-increment: page;
 
    @top-center {
        content: "Headline, yo!"
    }
 
    @bottom-right {
        counter-increment: page;
        content: "Page " counter(page);
    }
}

The counter-increment property is a bit special with the keyword page – it increments automatically according to the specification, so you don’t need it at all.

That rocks, right?! Totally want this in browsers now.

Edit – 26.03.2013: Actually there is another possible implementation for fixed headers and footers using position: fixed; elements as Robert Weber researched. Unfortunately this only works in Firefox, Opera and Internet Explorer with several quirks. Please read his comment.

A Word On Mobile

These days it has become more and more popular to visit web pages from your smartphone or tablet but I have never seen anyone printing a web page from such a device.

I am not aware of a browser that has the ability to print a page. But maybe this will come in the near future. Let me know if you know more about this.

Edit – 25.03.2013: As Cãtãlin Mariş points out, iOS has a feature to connect to a wireless printer and print a website. This uses Apple’s AirPrint services.

The Server-Side

This post does not take any server-side rendering methods to create style sheets into account. However there are some several non-browsers, print-oriented CSS implementations: WeasyPrint, PrinceXML or AntennaHouse and others implement many CSS features that browsers don’t.

So take a look at these libraries if you are in need of more consitend

Conclusion

As it turns out it is possible to handle simple structured web pages with the provided properties for print stylesheets. But when it comes to more complex applications you will easily reach the end of these possibilities.

As a result of the work that the editors put into new specifications such as the Paged Media Spec we will be able to deal with better solutions in the future.

Thanks

A big thank you goes out to Adrian Roselli and Simon Sapin for providing very valuable technical feedback for this article. Apart from that I want to thank Thomas Caspers for proofreading the post.

About CSS Variables

Please read about the updated syntax of CSS variables in the first and second update of this post.

Since a little bit more than a month (as of the time of writing) there is a Editor’s Draft for a CSS Variables Module by Google (Tab Atkins and Luke Macpherson) and Daniel Glazman. Just a few days ago the Working Draft was updated.
The first draft was written in 2008 by Daniel Glazman but was not added to the official specification. The new WD extends this proposal by Glazman.

Disclaimer: This article is part of a small series about the latest CSS working drafts. The first article in this series was about the CSS Hierarchies Module.

CSS Variables

The CSS Variables Module Level 1 suggests to use variables for data that is reused in stylesheets. These key-value storages provide the possibility to store “meaningless” data as you can do in HTML: Variable keys consist of a data--prefix and the variable name.

Any property name starting with the prefix “data-” is a data property. Data properties are defined to be valid but meaningless as they are meant solely for allowing authors to pass custom data around their page, similar to the custom data attributes in HTML.
Defining Variables With Data Properties – CSS Variables Editor’s Draft

Using data- as a prefix for variables is still in discussion and may likely be changed to something more “connected” to variables ($ or &).

Edit: The mailing-list www-style is discussing the use of data and Ian Muir wrote an article about the problem.

Syntax

Variables are defined by mapping them to the :root pseudo-class. The WD does not really explain why the variables must be declared on the root-element. Maybe it’s because the data needs to be bound to an element to not “fly around” in the global scope (which does not really exist in CSS).
Defined variables can also be set on every other element and overwrite the existing value of a variable.
So this is how you set variables.

To get a specific variable, you do not declare the variable-name but you call data as a function on a certain property with the variables name (without data--prefix) as an argument.

An Example

So here is an example:

/* Set data */
:root {
  data-main-color: #bada55;
}
 
/* Get data */
.foobar {
  color: data(main-color);
}

As said before, variables can be overwritten for specific elements. So we can add the declaration of the variable to .foobar:

.foobar {
  data-main-color: #fe57a1;
  color: data(main-color);
}

The color of .foobar is now #fes7a1 and not #bada55.

Real World Examples

Well, as this is an Editor’s Draft and pretty new it’s not being implemented in any browser.

I’ve created a test case on dabblet with vendor prefixes which tests the two examples above. I’ve run this test on the major browser alphas and nightlies.

Even though variables are not natively supported by CSS in any browser yet, we can use a very similar approach: All CSS preprocessors support variables. Here is an example with SASS:

/* Setting a variable */
$main-color: #bada55;
 
/* Get the variable's value */
.foobar {
  color: $main-color;
}

Conclusion

We can use variables with preprocessors today which is pretty rad. As with the CSS Hierarchies Module CSS in the future may support ideas that come from implementations in preprocessors somehow.
I think most developers are happy about these adoptions and will likely use it. But as it will take some time for all vendors to implement this feature – and even more time until browsers that don’t support such new features vanish – we will have to use preprocessors to get variables in our CSS working.


Update 19.08.2012

Since I wrote the last update the Editors Draft changed: The var()-function changed to use the var-glyph $ as it is known from SASS (described above).

It is now possible to call variables like this:

h1 {
  color: $some-color
}

While it still needs to be defined with the var prefix:

:root {
  var-some-color: #aaa;
}

As Tab Atkins describes in his blog this is going to change back to the old syntax I wrote about in the first place as this causes problems with further implementations of CSS (like variables for selectors and the hierarchy model).


Update 16.04.2012

Since last week the CSS Variables Module Level 1 is an actual Working Draft of the W3C.

It’s now possible to define variables with the var-prefix instead of data which is still pretty complicated. I wonder why they not adept an existing concept as in LESS or SASS.

Thus the data()-function changed accordingly to var().

Furthermore it’s possible to set variables on a certain element but use them in a more complex definition. An example might be the usage as follows (while elements with class important and primary are divs):

.important { var-color: red; }
.primary { var-color: blue; }
div { color: var(color); }

Also nestings for variables are possible:

:root {
  var-color: #ddd;
  var-border: 1px solid var(color);
}

The bright and shiny future

As I think there still are some issues with this Working Draft I like the fast step forward in making this a WD in only a view weeks.
So sooner or later variables will be part of the CSS specification and will be implemented in browsers. I hope this will be very soon.

About The CSS Hierarchies Module Level 3

Since the beginning of February there were some proposals for the CSS3 specification. These proposals are not yet part of the specification and will likely be changed until they get adopted by the CSSWG. One of these drafts is the CSS Hierarchies Module Level 3.

So what’s the Hierarchies Module? And why “Level 3”?

The Hierarchies Module is not exactly new. It exists since the very first steps of CSS and was first released in Dezember 1996 with CSS1. The CSS1 specification is still up, so check it out if you want to.

When you write CSS you always use selectors to target the element you want to style. This works pretty much straight-forward: The right-most simple selector is the one which get the declarations assigned that are defined in the ruleset.
These selectors define a certain hierarchy in your stylesheet.
Note: Please make sure to read Tab Atkins’ Reference for CSS Spec Terms.

An example

Today you would target some links in a navigation like this:

#nav ul li a { color: #000; }

If you’re smart and your markup allows you to do so, you may write:

#nav a { color: #000; }

The li-elements need to be inlined as you want a horizontal navigation:

#nav ul li { display: inline; }

Furthermore the navigation should be aligned on the right and all the links centered:

#nav ul { text-align: right; }
#nav ul li { text-align: center; }

This leaves us with a lot of repetition for the selectors.

#nav ul { text-align: right; }
#nav ul li { text-align: center; display: inline; }
#nav ul li a { color: #000; }

With the Level 3 proposal by Tab Atkins Jr and Shane Stephens (working for Google) this is about to get a little bit easier. The existing system will be extended with some new functionality. This is why it’s called Level 3. (Also it will likely be part of CSS 3 – and not 4 or 10 or something.)

What’s new in there?

Lately you saw the rise of CSS Preprocessors. Everyone has an opinion on this. The thing why so many developers use them is that they help to organize the CSS-code you are writing.
Preprocessors have brought up another idea of CSS hierarchies. And with the CSS Hierarchies Module Level 3 this has been adopted.

The specification draft allows you to nest your rules and use the &-character to reference a parent selector in a certain rule.

Here’s the example from above with the new hierarchy:

#nav ul {
    text-align: right;
    & li {
        text-align: center;
        display: inline;
        & a { color: #000; }
    }
}

As you can see there are no repetitions for the selectors as you can reference them by just writing & and nest them properly.

How can we use this today and when will it be ready for the “real world”?

As you may guess this is not implemented in any browser yet.

As this spec is written by two Google-guys it’s likely that this will be implemented in Chrome in the near future. At the moment this is not working with Chrome 19 (Canary) or WebKit Nightly.
I’ve made this Dabblet to check if the module is supported in a browser or not. caniuse.com does not provide any data for the Hierarchies Module yet.
Aside: Check my Dabblet Chrome App to view all your latest dabblets if you’re a Chrome user.

Tab Atkins proposed another style for nesting. To reference the parent selector you use @this instead of the &-character. Peter Beverloo wrote about this a year ago. Also Tab Atkins has an article about his further plans. This variant was not implement either and is replaced with the new draft for the specification. Anyway you could view the dabblet I’ve made for this propose.

Preprocessors

As mentioned above CSS preprocessors offer the chance to use something like hierarchies in there own way. Here are two examples:

SCSS (aka. SASS)

#nav ul {
    text-align: right;
    li {
        display: inline;
        a {
            color: #000;
            &:hover { color: gray; }
        }
    }
}

Stylus

#nav ul
    text-align right
    li
        display inline
        a
            color #000
            &:hover
                color grey

As you can see there is a difference in how preprocessors treat the &-character as a reference: In the CSS specification draft & is obligatory in every nested rule you write to reference the parent selector. Preprocessors need them only if there is a pseudo-class or -element or a combinator (such as ~ or >) used for a specific selector.

As I stated in the introduction it may happen that the specification will be changed until it becomes final or is adopted by the CSS Working Group. I recommend you follow the discussions about this topic in order to stay up to date.
When this specification will be implemented by one of the browser vendors it’s just a matter of weeks until it will be adopted by the others I guess.

But, as the draft states, this is not yet part of CSS:

This document is purely an Editor’s Draft. It has not yet been adopted by the Working Group, and should not be considered to be part of CSS.

~ CSS Hierarchies Module – Status

Opinion

Personally I hope that referencing the parent selector with & will not be in the final specification as it is now. It’s not needed as the rules are nested anyway and preprocessors nowadays treat them better.

Anyway the new nesting is pretty useful as it reduces the redundancy of writing selectors in CSS. In connection with other upcoming specifications like the CSS Variables Module Level 1 this is what is needed and will be helpful for every web-developer once it will be implemented in browsers.

Responsive Media

There is a big discussion going on at the moment covering the actual point of how to deal with images and media et al. on mobile-phones and other devices as there are some things that don’t work as on a desktop computer:

  • Bandwidth
  • Screen size
  • Performance / Velocity

The question is how to deliver responsive images on a mobile website.

You maybe use something like img { max-width: 100%; height: auto; } in your responsive design to prevent images from being bigger then the screen of a mobile device.

In most of the cases this shrinks images in its displayed size, which is a processor intensive thing to do – especially when you are on a mobile device and don’t have endless processor capacity this hurts.
The shrinking itself does not change the file-size that has to be loaded; it remains the same as on a desktop for example. As bandwidth is the bottleneck these days if you are on a mobile device, this is the issue where people want to see some improvement.

What can we do about it?

There are a couple of proposals and known techniques on how to solve the problem:

1. Resize images with PHP

This is something you could only do if you know the screen-size before you load the images them self. So you have to inject HTML through JavaScript for example and change the sources for images accordingly.

The Adaptive Images framework a similar technique. Check out the source on GitHub.

2. Request different images using data-attributes

An article by Nicolas Gallagher covers this method using CSS to detect which source would be best to use.

The method could work like this: You have an image which has a really small file size and is served for every device at first (mobile first approche).

<img src="image.jpg" alt="" data-src-600px="image-600px.jpg" />

Now you are going to change the file if the screen is bigger by using the content-property of CSS and its attr() function.

@media (min-device-width:600px) {
    img[data-src-600px] {
        content: attr(data-src-600px, url);
    }
}

Please have a look at the article for detailed information.

An idea that goes beyond the replacement of images with the attr()-function is the usage of content: url(myimage.jpg) replaced;. This is something suggested by Tab Atkins Jr. on the W3C www-styles mailing list – called replaced content.
Something about replaced content appears in the CSS-spec but it does not look to be exactly what Tab is referring to.

3. Introduce new attributes to the <img>-tag

Anselm Hannemann shares the idea of introducing a media-attribute that has some sort of “sizing-parameter”. It is supposed to be combined with the media-src-attribute which also has the sizing-parameter.
The HTML could look something like this:

<img src="myimage_xs.jpg"
media-xs="(min-device-width:320px and max-device-width:640px)" media-src-xs="myimage_xs.jpg"
media-m="(min-device-width:640px and max-device-width:1024px)" media-src-m="myimage_m.jpg"
media-xl="(min-device-width:1024px)" media-src-xl="myimage_xsl.jpg">

As you can see the media-attributes contain media-queries which describe when to take a certain image-source.

4. Using JavaScript

There are some ideas on how to deal with this topic using JavaScript.

The FilamentGroup for example published its “Responsive Images”-project on GitHub. They are using “Mobile-First” to present a small-sized image on every device and replace this with JavaScript on window load.
You can find out more about how it works on their blog. They also published a demo.

Peter-Paul Koch presented a possible way on how to combine media queries with JavaScript. Which is not really new I think but a good summery.

Another approach could be a new attribute for the script-tag: Scott Jehl suggested to call it preparse. The script could then be used to replace sources in HTML fitting the current client-need.

5. A new image-format containing different sizes

People aso had the idea of creating an own image-format which contains for example four layers with different image sizes. The image then “decides” which format to take and serves this to the client without its three sibling-layers.

At the moment there is a format called MrSID developed by LizardTech which can have one or more compression rates.

Another approach is the JPEG 2000 file-format. It can carry out different optimization-levels for images. Read more about it on the Wikipedia-page I linked above.

Media? But this was only about images…

Yup, right! Images are just one aspect when it comes to responsive media.
Videos for example are another thing. YouTube offers different video-sizes for watching. You have to choose manually which one to use. A possibility to select this resource automatically, build into the browser would be awesome!

JPEG 2000 has a video-equivalent developed by the same group of people as the JPEG-format called Motion JPEG 2000. Find more information about this here.

Conclusion

As it turns out many developers are not aware of the problems that come up with a real responsive design – even HTML5-specification writer are calling it “a niche problem”. This is why it is hard to develop a specification for a native API as for example Anselm Hannemann suggests.

But maybe the decision which technique might be best for solving the problem of serving responsive media has to be finished first before anything is spec’d up.

Moar!

Some more resources where the topic is discussed:

Thanks!

Thanks goes out to Anselm, for reading what I wrote and helping me with some further information.

A Travel Through Time – and Back

Somehow… <time> Disappeared

As you might have heard the <time>-element was removed from the HTML5 specification last saturday by Ian “Hixie” Hickson, the editor of the spec. Hixie decided to remove <time> and replace it by the more general <data>-element.

A question that came up: Why got<time> removed and why did nobody stop Hixie?

Well: There Google+. Also we talked about this issue on the (german) podcast Working Draft on monday. I was invited by Christian “Schepp” Schäfer to discuss about some stuff with himself and Marc.

Steve Faulkner was the first one (for what I noticed) that tweeted about that intensively and was really upset by the dropping. Furthermore it was his tweet that encouraged me to keep track of the whole story.

Steve explained on the the mailing-list of the W3C why he likes to revert the changes made by Hixie the day before. Others also liked the time-element and requested a revert.

There were some pretty good blog posts about that topic, as for instance

As it turns out <time> is wildly in use all over the web:

  • the WordPress twentyeleven-theme uses it
  • The Boston Globe makes use of it
  • I’m using it on this page
  • And many others too…

As so many people where effected by the change that was made to the spec and many people though it was a bad decision there was hope that this story was not over yet… And it wasn’t.

Again Steve Faulkner tweeted:

“I feel confident that <time> will be back in the W3C HTML5 specification by the end of the week”

~ Steve Faulkner, 31. Oct 2011 via Twitter

This was a decent statement as you can say by today.
There were proposals on how to deal with <time> and how to improve it for the future and get it back into the spec. A leading role in this process is held by Tantek Çelik. Read his comment on Bruce Lawson’s post. Also Stephanie Sullivan Rewis has some interesting thoughts.

And then – the Turningpoint

Currently the TPAC 2011 is happening which is a conference and meeting of the W3C and its members.
At (Please notice my use of <time> in this case. Nice, right… right?) people of the W3C HTML Working Group met and discussed about <time> and its removal. You could have followed the discussion on IRC on W3C’s channel #html-wg. Here you can find the “minutes” (a transcription) of it. Tantek added this as a point for discussion to the Agenda.

As this all was said, there was a mail on the mailing-list by the Chairs of the HTML WG asking the editor of the spec (Hixie) “for a revert of this change to be completed no later than the end of day on Tuesday 8th of November”. If Hixie will not change this until Tuesday the Chairs will ask the W3C staff “to make this change”. What ever this means then… I have no idea.

Today Tantek began to define some new requirements for the <time>-element and its attribute datetime (especially the syntax of the mentioned attribute).

So what’s the conclusion now?

All the things I mentioned above show how strong the community is and how many people try to get the best out of the tools we have.

Hixie’s decision to remove the <time>-element in favor of the <data>-element was not found democratically by everyone contributing to the HTML5 spec but was a bossy behavior.

Personally I learnd a lot about the process within the W3C, the WHATWG, how the specification is build, and so on asf… This was pretty good and I feel good about how things work.

I hope there are more people who like keep a little bit more track of what is going on with all the new stuff and be part of decisions that are made.

Thank you for reading all the words I wrote.

Thank you Steve, Tantek, thank you Eric Eggers, Shelley Powers, thank you everyone who was able to do something about the odd removal of <time>. You guys rockkk!

Resize Elements with CSS3

The CSS3-spec is full of wonderful things. Sometimes things that are not so desperately needed as others but anyway… good to have them.

One of these more or less needed properties might be resize. It is part of the CSS3 Basic User Interface Module. What is really useful with resize is the ability to restrict the resizing of textarea for example. But it is possible to resize every element you’d like to as this demo by Simurai shows.

There are four values for resize that are kinda logical:

  • none: no resizing at all
  • horizontal: resizing only horizontal
  • vertical: resizing only… vertical
  • both: yeah, well… pretty obvious, right?!

Robert Nyman created this demo using the resize-property. You should also check out Louis’ article that’s pretty great. And: the MDN docs about resize. You can also read more about this topic at Stackoverflow.

Pseudo-Elements in Print-Styles for References in Links

This morning @t3node asked me about something CSS-related. This was kinda new for me because he never did this before I guess… He showed me a website he had printed and asked me to explain him, how it is possible to show links in printed websites with their reference printed next to it. He was kinda upset why not every frontend-developer includes this in his/her stylesheet when it comes to designing a new website. I wanted to explain everything that’s related to this topic that I’ve ever heard of but he asked me to write this blogpost as he is not pretty used to CSS and stuff.

Styles dedicated to print

To get this feature for a website you need to define some print styles.

1. link-Tag

It is possible to load up a stylesheet that is dedicated to server styles only for media print with

<link rel="stylesheet" href="css/some-print-styles.css" media="print">

Where media="print" is the important part here as it tells the browser to apply all styles it contains only for print-views of the website. I do not recommend this method because of some drawbacks for performace:

  • The client has to load the CSS-file even if it does not need it
  • This implies another HTTP-request
  • Even though it is not a lot: the browser needs to render the styles

2. @import in CSS-file

Another possible way to render styles only in print is to include a file with @import url("some-print-styles.css") print. This also has drawbacks on performance. Even more as the link-method as files get blocked for downloading in your browser if @importis used.

3. Inline styles

For inline styles it is also possible to define an attribute media.

<style media="print">
  .element {…}
</style>

4. Media queries

My favorite method to include styles for print are media-queries. It is possible to add styles for print via @media print. Maybe you are familiar with this because of media-queries dedicated to mobile devices. Once you’ve set up this environment you can start adding some styles for any print of your site. I recommend to add display: none;for elements that are not pretty important in a printed-version. This could be the sidebar and the footer or the navigation. The thing why I’m originally writing this is how to include the reference of a link in a printed version of a website. So I’m just going for it. It is just one pretty little rule!

Pseudo-Elements for generated content

A good use-case for pseudo-elements:

a[href]:after {
  content: " (" attr(href) ")";
}

a[href] selects all links with the attribute href set and creates content :after it. attr(href) tells the browser to use this attribute as content. You may want to select a little bit different as you don’t want to display references in the navigation or so for instance. HTML5 Boilerplate makes use of this, too. These little features are why I love it so much. Go check it out and contribute. Chris Coyier has a pretty awesome article, tutorial and demo at CSS-Tricks which has nothing to do with print but describes the use of pseudo-elements and contentreally good. You should definitely read this.

Browsersupport

@media print is supported in all browsers for what I know. Except Internet Explorer 7 every browser supports :after at least good enough that content works with it. The bottleneck here seems to be attr(href). As I researched this it turned out that generated content with attr() is valid CSS 2.1. The spec adds a warningon this vary topic:

In CSS 2.1, it is not possible to refer to attribute values for other elements than the subject of the selector.

You will find more information on attr() in the CSS3 Specification. It seems as every browser (that is actually used) is going to support this except IE7 and below. I’ve set up this demo so you can test it in your favorite browser and edit it yourself. I would be glad if you share your results and thoughts on this topic in the comments.

Conclusion

As it turns out it’s kind of the right to support straightforward things. I believe everybody could at least add some default styles for print to a new website like HTML5 Boilerplate does by default. The little trick with pseudo-elements can also be pretty useful for other elements like abbr aso. Later on I noticed that @t3nodes website does not support this feature for print either. Maybe it will after he has read this post. My website and this blog do not make any special use of printed styles as I think it is not necessary that anyone prints out my blogposts. I don’t like to print thinks for myself as I believe that you could save some paper in regards to environment. But this is your decision – or the one of your customer.   Edit Thanks to Nicolas for his hint about the difference between pseudo-elements and pseudo-classes. You should also consider using ::after instead of :after. But be aware that IE8 does not support this.

Offer Files as Download with a@download

So the spec introduces a new attribute on a-tags (so called “links” – this may be new to you ;-)) called download (short: a@download – this technique of connecting attributes with tags is written up and documented by Mathias Bynens).

When you link to a file like an image or a PDF-document it will be displayed within the browser normally. The download-attribute in links prevents this behavior and offers the file as a download in your browser.

Definition

The spec allows the attribute for having a value. This value can be a string which defines the name of the downloaded file. As a default the browser takes the file’s original name.

And this is what it could look like in HTML:

<a href="path/to/file/file.png" download="a-nice-image.png">Download this file</a>

The value of the download-attribute overwrites the filename with a-nice-image.png.

The Content-Disposition-header can overwrite the name for the file.

This really nice demo exports a written text and offers it as download (but be aware of browser-support – see below).

Browsersupport

The download-attribute is not supported very good at the moment of writing this article.
Chrome supports it since its version 14. Version 14 is only a view weeks away from the stable release.
Firefox 8alpha (Aurora-channel) does not support it as far as I experienced it. I did not find anything about any intensions when Mozilla will include it.
And the other ones? No support yet!

So, what’s the fallback?

There are other techniques to serve a file that will be offered as a downloads in the browser. For instance you can use an HTTP-Header that’s a mime-type that the browser does not know.

Here is an example with PHP:

header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename="some-file-name.ext"');

You should then open the download in a new window or tab, or in an iframe to prevent any stupid browser-behavior.

More about this issue here.

CSS3: Auto Hyphenation for Text-Elements

In browsers we do not have the ability to automatically hyphenate continuous text. This is an issue when you are using text-align: justify; for instance because the text may look really bad.

I want to write about this topic because of the discussion that came up at the HTML5 Boilerpates issue-list and this blogpost at Fontdeck Blog.

The specification says:

Hyphenation means splitting words to improve the layout of paragraphs.

CSS3 Properties

CSS3 adds six properties to the list of useful thing. These are:

  • The most important one is hyphens. More to this one later.
  • You can add dictionary-files with hyphenate-resource so the browser has a better chance to render your text with the right hyphenation.
  • hyphenate-before sets a minimum number of characters before the hyphenation.
  • hyphenate-after does the same as hyphenate-before but for characters after the hyphenation.
  • hyphenate-lines defines about how many lines a hyphenated word is written at a maximum.
  • with hyphenate-character you can specify which HTML-entity should be used, e.g. \2010.

The main property of this stack is hyphens. It accepts one of three values: none, manual or auto. The default one is manual, where you can set hyphens via &shy;. auto it the better one for continuous text while words get split if possible and available. And none does not hyphenate at all even if there is a character set for a possible line break in a certain word.

There is one thing you have to be aware of if you use this property: You have to define a lang-attribute on an element that carries text that should be hyphenated.

I made this jsFidde where no lang-attribute is set. It does not work in Firefox. With this attribute set, it works quite good in Firefox, too (thx to 91media).

Browsersupport

Currently hyphens is supported in Safari 5.1 and Firefox 6. For Firefox 6 the lang-attribute must be set as mentioned above. Also it only supports english.
It is not working in Chrome 15.

You have to add some vendor-prefixes for support in browsers:

.element {
  -webkit-hyphens: auto;
     -moz-hyphens: auto;
          hyphens: auto;
}

There is a polyfill for this. It’s working with JS and inserts the HTML special-char &shy; where it fits. It supports many languages. This polyfill also uses the CSS-property where it is possible.

Edit:
Thanks to Ash for letting me know about my mistake using hyphen instead of hyphens.

Update

I just found this issue at the Modernizr issue-tracker where a test for the hyphens-attribute is discussed. There is a test in the latest GitHub-Version for it. Search for csshyphens.

Update 2: 12.11.2012

-webkit-hyphens has now landed in Chrome Beta.