Entries tagged with ‘CSS’

Display:

Tags

  1. @font-face in IE: Making Web Fonts Work

    All Hallows’ Eve seems the perfect time for something a little spooky. Getting @font-face working in IE may just be spooky enough. As you probably know @font-face already works in Safari 3 via WebKit and is supported in the latest Firefox 3.1 beta. With IE, that means around 75% of the world audience could see custom typefaces today if their EULAs allowed it. Fortunately, there are good free faces available to us already, as well as some commercial faces that permit embedding. Fontin is one of them and I’ve built it into this example page:

    Before we get into the nitty-gritty of making this work, which you can skip to if you wish, I thought a little history and a brief summary of the current status of the web fonts debate might be useful.

    Web Fonts: Then & Now

    Web fonts have been with us for a decade. They were an original part of the CSS2 recommendation in 1998. Recently, the godfather of CSS, Håkon Wium Lie, brought them sharply into focus with articles in CNet and A List Apart. The ironic thing is, IE has supported web fonts using the Embedded Open Type (EOT) format since 1997. The problem was that EOT was a proprietary format, belonging to Microsoft. Not for much longer: it’s been submitted to the W3C and is going through the process towards becoming a web standard.

    Since the debate opened up, the web and type communities have both been busy discussing how the future will unfold. More collaboration between the disciplines would be beneficial to both, and I’d encourage any interested designers or developers to get involved with organisations like the Association Typographique International (ATypI).

    Recently, Bert Bos of the W3C paid a visit to the ATypI Conference in St Petersburg to meet with type designers face to face. His summary of the current situation is essential reading. The debate has continued apace on the ATypI mailing list, which unfortunately has no public archives. However, if you are member of the ATypI, you can see this summary about the conference panel on web fonts by Nadine Chahine that started the debate in earnest. Simply put, type designers seem anxious about @font-face linking making it too easy to steal a font. Both Microsoft’s EOT format and direct font linking are under consideration with EOT a favourite with many. However, rather than paraphrase a wide-ranging set of opinions, I’d encourage you to join the ATypI yourselves as designers and developers to participate or observe.

    If you have other favourite comments or posts about the future of web fonts, please add them to the comments.

    As a designer, I want a straightforward way of licensing and including fonts for my work. I will pay, respect the rights of type designers as I expect mine to be respected, then get on with the glorious business of merging content with type. It’s not as simple as it sounds, though. The licensing of fonts, and the protection of the rights of smaller designers in particular, is a sticky issue. DRM does not work, so what then? Richard Rutter has shared thoughtful insights which are very much worth a read. My view is that I would be perfectly prepared to pay a separate or extra licence fee to use quality fonts on the Web. I would have no problem selling this to my clients. Embedding or linking to fonts has to be straightforward though. I get paid to think about, plan and implement design, not grapple with obstructive software (more on that later). If fonts were delivered through a third-party web service as Richard suggests, the one proviso must be that it would have to be done by someone who knows exactly what it means to scale a service for millions of users. Like most designers though, I have very little knowledge of the real security and scalability issues, but hope to see a comment from a real security expert, shortly.

    User agents are currently taking divergent routes. Bert Bos’ summary reports:

    Mozilla has stated that they don’t want EOT. But they are not opposed to letting the browser check the license, as evidenced by the proposal to let HTTP headers carry license data.

    Microsoft has said that it is impossible for them to support linking to native OpenType as long as font vendors oppose it.

    Apple’s Safari has implemented font download with no checking of licenses. They said they are against EOT, but would not be against browsers checking licenses, e.g., using Mozilla’s proposal.

    Opera remarked that there are more existing and announced implementations for downloading native OpenType than for EOT. They conclude that the market apparently doesn’t need EOT and thus they see no need to support it themselves either. W3C’s limited resources should be spend on more important standards.

    That means that designers and developers have the same perennial problem: Two different implementations to achieve the same result. Safari 3 and Firefox 3.1 beta both support direct linking to OpenType (.otf) font files. Presumably Opera will soon. Only IE 4 to IE 7 support Embedded Open Type (.eot) files. IE8 does not, but will at some point. So, to see Fontin display in standards complaint browsers like Safari 3 and IE, we need to provide two separate fonts.

    @font-face Example

    The @font-face example uses Fontin Regular by Jos Buivenga — a free face kindly provided by Jos with a licensing permitting embedding with attribution. Jos also has many other fine faces available via his foundry site, Exljbris. The example is a quick one using a traditional scale, with all of the CSS available in the <head> of the file.

    1. Set the basic font-family:

      h1, h2, h3, p, td{
      font-family:'Fontin-Regular', georgia, serif;
      }
      

      Notice the 'Fontin-Regular' name — this is an arbitrary name that can be whatever you like. All it does is tell the browser when to apply the font file referenced in the @font-face rule.

    2. @font-face and .otf for standards compliant browsers:

      Ed: White space inserted for clarity.

      @font-face{
      font-family:'Fontin-Regular';
      src: url('Fontin-Regular.otf') format('opentype');
      }

      Note the 'Fontin-Regular' name, again. This rules basically tells the browser, when the @font-face is set to 'Fontin-Regular', use the font found at this URL.

      Screen sample of Fontin Regular in Safari 3 set at 16px with 24px line height from the example:

      Fontin in Safari 3

      When Safari renders the page, it will look for the font file, then render the text accordingly. There’s a slight delay as WebKit works. In the example you might notice that the text not requiring the loading of a font file renders quickly, but the rest is blank until the browser catches up. For reference, the Fontin-Regular.otf file is 32KB in size. Some font files can be much larger.

    3. Create the .eot file with WEFT:

      To do this you will need to download and install WEFT3, a Microsoft application for creating EOT files from TT fonts. WEFT is not able to create EOT files from an OTF. It must be converted to a TrueType file, first. WEFT is the only tool for this as far as I’m aware, although I believe there is an open source one in development. If it wasn’t for WEFT, embedding EOT files would be easy. What I want WEFT to do is convert the font to EOT, and allow me to create a subset if required. It does that, but in a nightmarish, frighteningly over-complicated way. Perfect for an All Hallows’ Eve entry. Here are a few tips I learnt the hard way:

      1. WEFT requires the URL of the page or site where the EOT font will be used. It will then ‘scan’ the pages by crawling the site to see what glyphs are used and try and create a subset of the EOT file accordingly. If it refuses to analyse a valid URL as it did for me, get granular and specify pages or sub-directories in your information architecture.
      2. If you’re using WEFT via Parallels and XP Pro, it may refuse to add some fonts in your windows/fonts directory to its database of available fonts. Try using a standalone PC if you can. I haven’t tested in any other virtual machine.
      3. Use the wizard to set up your project, but after that try it manually using the View menu item to see what fonts are available to convert, and the Tools menu item to convert them.
      4. WEFT will try to save the EOT file to a remote location. You can over-ride this manually to save the file wherever you please for you to upload yourself.
      5. Disable your original OTF fonts on your system before testing (obvious but worth a prompt).

      Be warned, WEFT is awful to use, in every way. It did not work for me running Parallels with XP Pro on a Mac. 7th Nov: After more experiments, Weft will accept TrueType (.ttf) files in Parallels. It also worked with the gracious help of Jon Gibbins and his standalone PC running XP Pro. Because it is so painful, I cannot give support for WEFT. You can try the Microsoft WEFT user community, but I can’t comment as to its usefulness, and I could not find any other support avenues.

      Hopefully, you now have an .eot file to use.

    4. @font-face and .eot for IE using conditional comments:

      Ed: White space inserted for clarity.

      <!--[if IE]>
      <style type="text/css” media="screen">
      
      @font-face{
      font-family:'Fontin-Regular';
      src: url('Fontin-Regular.eot');
      }
      
      </style>
      <![endif]-->
      

      These are screen samples from IE:

      Screen sample of Fontin Regular in IE6 set at 16px with 24px line height from the example:

      Fontin in IE6

      Notice the bar missing from the capital ‘A’ towards the end of the second line. The tyepface designer, Jos Buivenga is currently looking into the font hinting, with input from John Boardley.

      IE7 sample:

      Fontin in IE7

    See a full size Safari 3 screenshot, and IE6 screenshot on Flickr.

    That’s all! Try the example in different browsers to see how it works for yourself (but please don’t blame me for ClearType’s poor anti-alias at larger font sizes).

    Summary

    We have only a few web fonts with a EULA that permits embedding right now, unless they are free. Please respect the EULAs of any typefaces you try out until the type community resolves the issue for all commercial fonts.

    My feeling after doing this is that EOT has potential advantages in file size over OTF, but OTF files could always be edited (as far as I’m aware) to create subsets just like EOT. Although EOT is not a DRM solution per se, it feels like one. If it achieves widespread acceptance, no doubt some clever soul will be reverse-engineering an OTF file from EOT before too long.

    What we need to encourage designers and developers to use EOT today is a good tool to create EOT files in the first place. Perhaps even one hosted remotely, where we can buy a licence, convert the font to EOT, grab the same OTF subset for complaint browsers, and get the work using the typefaces we’ve always dreamed of. WEFT is not the tool right now to enable EOT usage. In fact it discourages it.

    Regardless of what security is implemented, the font file will have to be on the audience’s machine somewhere, even temporarily. ‘Defense in depth’ is a term used by web app security experts. It would seem that the question is how much depth will satisfy foundries and type designers, and what form that depth will take.

    As a designer, I can only speak for myself to say that if OTF and TTF were supported, regardless of how easy it was to steal the file, I would still pay as required by the EULA. I have a strong feeling the vast majority of my colleagues feel exactly the same.

    Share

  2. Typographers, lend me your pain

    Dear web typographers and designers, I need your help (and your woes!) A couple of days back, Jason Teague, Director of Web Design for AOL Global Programming and member of the W3C CSS3 Working Group made a request for input from designers around the CSS fonts and CSS web fonts modules. He has volunteered to be an advocate for them, and wants our thoughts and feedback on the way forward. It’s a welcome move, and a veritable bag of snakes he’s opening, so congratulations to Jason for volunteering to take the pain. I think we should help him out.

    CSS

    For my part, I’m planning to respond in detail, supported by a few test cases and examples of current rendering. Wish lists are great, but I think empirical evidence is more useful when identifying current issues and areas for improvement in the recommendations. So, if you’re a web typographer or designer and have come across problems or issues that might be worth cataloging, let me know what they are. I’ll promise to try and put together a test case and convert anecdotes to science if I’m able. Alternatively, you can just throw your thoughts into the comments for Jason’s article.

    As an example of what I think might be useful, I’m planning on discussing classic type setting techniques that are either badly supported or absent like old-style versus lining versus small-cap numerals, raised or drop caps, granular glyph weights, ligatures, baseline fixing, etc. I’ll also be mentioning browser-specific hacks I use to achieve better rendering like setting a miniscule opacity value in Firefox on OSX to de-bloat the glyphs and improve larger-size anti-aliasing.

    What do you think?

    Share

  3. Naked in Tahiti (where’s Ms CSS?)

    Naked!

    Naked again. Why, oh why every year do I feel the urge to cast off the perfidity of style and expose my structure to the world? A question never to be answered, but merely enjoyed on CSS naked day!

    Love my semanticness (sp?). Love my form, my structure, my HTML, your browser (which is actually styling the HTML right now,) and markup in general raw and unabridged.

    Hey, on an unrelated note, did I tell you about that time in The Seychelles when I was naked and kinda playing guitar with my…

    Oi! You have a filthy mind. Enjoy the day folks, long may the tradition continue!

    Share

  4. Conditional Comments after Installing IE8 beta

    Overcoming daft hurdles before work can even start is a pain. Getting multiple versions of IE working used to be one of them until Yousif Al Saif’s excellent Multiple IE installer came along. Microsoft have a commitment to 10 years of backwards compatibility. Therefore, they should be the ones to make it easy for designers to test interfaces in multiple versions of IE. If only that were true. The virtual PC image for IE6 is painful to try and use in Vista Ultimate on Parallels. So much so that I gave up, installed XP and went back to using Multiple IE.

    After installing IE8 beta, conditional comments stopped working for other versions of IE. I sighed. There’s an easy fix though. Just re-install Multiple IE and conditional comments support will be back for IE6 and under.

    By rights, Microsoft should pay Yousif Al Saif for the service he’s provided to designers. Wouldn’t that be a nice thought? Perhaps a few donations from folks like us will be reward enough.

    Share

  5. Adios, IE8 Meta Mayhem!

    I’ve been holding back on a comment on the recent furor about the IE8 meta http-equiv switch. Mainly because the great and the good had it covered, but also because there was already a possible workaround, which John Resig pointed out: Use a HTML5 DOCTYPE.

    Dean Hachamovitch and the IE team put out the fire yesterday with a switch of their own:

    “We’ve decided that IE8 will, by default, interpret web content in the most standards compliant way it can.”

    Great news! Now the legacy application vendors using IE as the platform, and relying on less-than-perfect rendering will bear the burden of telling IE which rendering engine they need. (Another radical idea might be for folks who are refactoring applications to use conditional comments like any good self-respecting developer should.) At least, with this announcement, the folks producing standards-driven code will not face the bizarre requirement of having to tell IE8 to not use IE7’s rendering engine. Makes sense to me guys, what took you so long? OK, the problem is more complex than that. After all, as Nigel Parker of Microsoft pointed out in his follow-up post to Kiwi Baacamp where he entered the debate:

    “Microsoft’s view [is] to support backwards compatibility for at least 10 years…”

    By anyone’s measure that’s a hefty commitment, and probably leads the field for backwards compatibility. Even more so when you consider that most new “killer apps” are targeted at the cool kids using the latest OS or browser, and often don’t work without Javascript. (Nudge, nudge Twitter.) A fact that always concerns me when you consider that “universality” is at risk of becoming a hackneyed word, and there’s a whole world out there getting online, often with less money than we spend on Starbucks, and the equipment to prove it.

    Anyway, I digress. Congratulations to the IE team and the collective intelligence in our community for reaching scientific solutions, intuitively. It just goes to show all the cynics out there that, as well a flaming each other, we also have a rare capacity for collectively recognising Robert M Pirsig’s metaphysics of quality.

    Share

  6. Designer PHP: A Dynamic Menu with If and Else

    Recycling PHP and HTML

    In the simple PHP include article I covered how to re-use one file in many pages. If you’re new to using PHP, read that first. Now it’s time to make file includes a bit more useful. In this article, we’ll include one file for main navigation, but make individual menu items “live” depending on the page they appear on.

    This is an article in the “Designer PHP” series of guides to using PHP for interface production. Previously:

    1. A Simple Include

    To perform this feat, we need to do three things:

    1. Declare a variable on each page to tell the menu what markup to display.
    2. Create a file with “live” and regular markup for each menu item. Add PHP to enable us to switch the markup according to the variable.
    3. Include the menu on every page.

    Declare the PHP Variable

    The variable declaration must be in every page the menu will appear on. It must be before the line of code that includes the menu so the menu can pick it up. I would normally insert it above the <!DOCTYPE… to separate the PHP from my HTML as much as possible. This is the variable declaration for the home page:

    (This variable declaration or PHP statement has two key parts: The variable reference, or name $page, and the variable value "home".)

    <?php 
    $page = 'home'; 
    ?>
    <!DOCTYPE…
    
    1. The variable name $page does not change. You can change it to whatever you like, just make sure it’s the same on every page.
    2. The value 'home' will be different for each page to tell the menu what to display.

    I usually have the value match the area of the site, so in the example we’re building it will be 'home' on the home page, 'about' on the about page, and so on. You can change the value to whatever you like, and have as many values as you need for individual pages.

    Create the Menu File to be Included

    For our purposes, we’re going to create a dynamic menu for a fictitious site with three pages: “Home”, “About” and “Contact”. You can extend this to apply to as many pages as you like. This is the basic HTML for the menu:

    <div id="nav">
    <ul>
    <li><a href="index.php">Home</a></li>
    <li><a href="about.php">About</a></li>
    <li><a href="contact.php">Contact</a></li>
    </ul>
    </div>
    

    We want two different sets of markup for each menu item: “live” markup and regular markup. In this example we’re going to attach a class to the “live” item — <li class="live"> — and wrap the link in an <em> to differentiate it even if styles are disabled. For example, on the home page, the “live” home menu item will end up looking like this:

    <li class="live">
    <em><a href="index.php">Home</a></em>
    </li>
    

    To switch between “live” and regular markup, we will use PHP “if, and else statements”. This is the menu HTML with PHP:

    (White space and line breaks inserted for legibility. PHP is emphasised in red. Disable styles to see it in italics if you need to.)

    <div id="nav">
    <ul>
    
    <?php if ($page == 'home') { ?>
    <li class="live">
    <em><a href="index.php">Home</a></em>
    </li>
    <?php } else { ?>
    <li><a href="index.php">Home</a></li>
    <?php } ?>
    
    <?php if ($page == 'about') { ?>
    <li class="live">
    <em><a href="about.php">About</a></em>
    </li>
    <?php } else { ?>
    <li><a href="about.php">About</a></li>
    <?php } ?>
    
    <?php if ($page == 'contact') { ?>
    <li class="live">
    <em><a href="contact.php">Contact</a></em>
    </li>
    <?php } else { ?>
    <li><a href="contact.php">Contact</a></li>
    <?php } ?>
    
    </ul>
    </div>
    

    Copy the code to a new file in your editor. Save it as nav.php inside an inc directory in your site root.

    I have deliberately separated the PHP and HTML as much as possible. There are other ways to achieve the same result, but this removes PHP completely from within HTML tags, hopefully making it easier to read and edit.

    Let me explain what the PHP does: Each menu item is marked up in two different ways: the “live” version and a regular version. The variable we declared tells the PHP in the menu which to display. For example, if $page = 'home'; is declared, the if statement ( <?php if ($page == 'home') { ?> ) will display the “live” markup. If home is not declared then the <?php } else { ?> statement takes over, and the regular markup is displayed.

    To make any of the other menu items “live”, you adjust the variable. The menu picks it up and switches the HTML. Simple. That’s our menu created and ready for use. The next step is to include it on every page.

    Include the Menu

    To do this we use the same technique explained in the simple include article, except this time we’re including the menu file, which we’ve called nav.php. This is the PHP you need:

    <?php include 'inc/nav.php'; ?>
    

    Insert that in each page at the point you wish the menu to be displayed. The path ( 'inc/nav.php' ) pointing to the nav.php file is relative — make sure you change it if your pages are not all in the site root. Each of your site pages will now look something like this (with the variable value * edited as required):

    <?php 
    $page='*'; 
    ?>
    <!DOCTYPE… >
    <html>
    <head>… </head>
    <body>
    
    <?php include 'inc/nav.php'; ?>
    
    …content
    
    </body>
    </html>
    

    That’s all! Now you can get to the fun bit of styling your menu with CSS. If you need to change anything, you simply edit the nav.php file and every page will be updated. Easy, isn’t it? Let’s end with a few tips about errors and security.

    PHP Error Debugging

    If you get a heap of PHP errors on a page instead of the menu, the chances are your include file path is wrong. Check it is pointing correctly to nav.php from the location of the page calling it.

    It’s useful to know that you can navigate straight to the include file directly in your browser and see the markup.

    (E.g. http://yoursite.com/inc/nav.php)

    If the file path is wrong, you will get a 404 error.

    If no menu items are active, or one is incorrectly active in a certain page, check the variable declared at the top of the page. Does it match the on in the if condition that precedes the item you want “live” in nav.php?

    If you’ve done all that, and you’re still having problems, check your syntax line by line. The chances are you’ve missed a tiny mistake. It’s a pain but a good way to learn.

    Security

    I grabbed a moment with web application security guru, Chris Shiflett to have him check my PHP. This is what he said:

    Whenever you’re working with a server-side programming language such as PHP, it’s good to be aware of potential security problems, because a simple mistake is all it takes to create one. If you follow Jon’s example, you’re safe, but what happens when you need to modify it to suit your own unique needs?

    Rather than complicate a wonderful tutorial, I’ll just point out that you should research further before doing either of the following:

    1. Add any additional PHP code to your includes.
    2. Use a variable in your include statement, e.g. include "inc/$template".

    If you need to do either of the above, you should first read a little more about remote code execution.

    Further Reading

    Control structures on PHP.net

    Can You Translate?

    After a wonderful response to the em and elastic layout article, I’d love to hear from anyone who’d like to translate this, or any other article in the series. I’ll be happy to host your work, like the previous Italian translation, or you’re welcome to publish it yourself. Just drop me a line.

    Share

  7. Complex Type: CSS Fix, ClearType Miss

    When an elusive penny drops, it’s always a good moment. Earlier today, I was thinking about the complex type rendering problem of a few days back. Skim that post, before you carry on and things will make much more sense.

    Suddenly, I realised what the solution was, and fixed the IE7 CSS problem in 5 minutes: After giving every element some padding and an invisible border—effectively forcing IE to recognise the element dimensions—it now renders the glyphs properly and doesn’t cut off loops or terminals that are outside the conventional em. Tinkering afterwards took another two hours but now the homepage has a new type experiment type folly for the masthead!

    So that’s the CSS sorted. I bumped into a IE7 problem with Eric Meyer’s unitless line heights along the way too, but that needs more research.

    Unfortunately, the ClearType anti-aliasing problem is out of my control. We simply can’t tell Windows to not use it, or to do it better. That’s up to users themselves, or Microsoft. So, for anyone looking at this site using Vista with ClearType enabled, here’s what you're missing:

    Safari screenshot

    Fig 1. OS X/Safari 2 screenshot of the masthead.

    For those of you lucky enough to be viewing using a Mac, or Safari on Windows, here’s what you're not missing:

    IE7 screenshot

    Fig 2. Parallels/Vista/IE7 screenshot of the masthead.

    The difference is stark. Even Windows standard rendering smooths large-sized text better than this. Update: See for yourself:

    Screenshot in IE7 using standard font rendering

    Fig 3. Parallels/Vista/IE7 with ClearType switched for standard rendering.

    ClearType seems to get worse as the font size increases. It sounds impossible that ClearType could be so bad, but my copy of Vista is a virgin Vista Ultimate, running on Parallels. No settings have been changed at all, and the only software installed apart from standard applications are browsers and anti-virus.

    So, there we have it, I predicted my own pedantry wouldn’t allow me to leave it be. With character predilections, as with rendering engines, knowing is only half the battle.

    Let me know what you think of the masthead type. You might even see it completely differently to me with a similar configuration. I’d be very interested in seeing a screenshot. I've not tested it in IE6, so bear with me while I get around to that. Is it worth keeping, even with the absence of decent smoothing in IE7/Vista?

    Share

  8. Rendering Complex Type—Who’s got the Love?

    The home page for this site was always temporary. After losing a year in distractions, work and prevarication I finally caved and whipped it together in a day so I could launch.

    Earlier this week I needed a timeout between sprints of development on our latest project, so I started to play with an idea for the masthead: A celebration of Web font letterforms with a complex <h1>.

    17/11/07: Updated in Complex Type: CSS Fix, ClearType Miss.

    This is where I paused just before I started testing in other browsers:

    Fig 1: Screenshot from Firefox 2 / Mac OS X 10.4.10.

    Jontangerine rendered with complex CSS in Firefox2

    I thought it was fun. I hadn’t yet locked all the distances to the pixel grid, and there was still more to do, but it seemed pretty close in Safari 2 as well.

    Fig 2: Safari 2 / Mac OS X.

    Jontangerine rendered with complex CSS in Safari 2

    Opera 9 also had it right. It also happens to be my favourite browser that I don’t use. If it had a stripped–down version with Chris Pederick’s Web Developer Toolbar you’d have to pay me not to set it as default, it’s core really is that good.

    Fig 3: Opera 9 / Mac OS X. Opera 9 is the only browser in the group to pass the Acid2 test.

    Jontangerine rendered with complex CSS in Opera 9

    Then I fired up IE7 on Vista, running it in Parallels and viewing it on an Apple Cinema Screen. Big Mistake.

    Fig 4: IE7 / Windows Vista Ultimate.

    Jontangerine rendered with complex CSS in IE7

    I can’t even begin to analyse the multiple problems with the rendering of my (albeit complex) type sample in IE7. From Vista’s ClearType jaggies to IE7’s CSS issues it’s simply carnage and a veritable type–crime; a smörgåsbord of bad rendering served with a mallet and a scowl.

    OK, I confess, I despaired for a second, hence the wry rant. I guess I’m asking too much of the browser. Maybe. However, surely we should step out of the cosy confines of tried and trusted methods, and let the creative beastie loose in the privacy of our own websites? Hell, under the hood this is just POSH with a few superfluous <span>s thrown in and a bit of CSS.

    Thinking With Type by Ellen Lupton

    In the very first line of the introduction to her fantastic book, Thinking With Type, Ellen Lupton writes:

    The organisation of letters on a blank page—or screen—are the designer’s most basic challenge.

    Perhaps that should apply to browsers too?

    Some of you may have more insight into these problems, and approach them as an intellectual challenge. I’d be interested in seeing any evidence or suggestions you have.

    In a previous article on core Web font rendering I’ve delved into the platform and agent differences, but this is more an emotional reaction. My heart says, “bollocks!” I know I’ll be drawn back to trying to find a way around the problems though, much in the same way as I was with the current logotype on the homepage. Until then, I leave you with the test page so you can hurt yourself with IE7 too, should you have the urge.

    Share

  9. The Incredible Em & Elastic Layouts with CSS

    Elastigirl saying “I’m an em” and Mr Incredible saying “and I’m a PX”

    Almost a year ago, Ty Gossman over at Stylegala asked me to write an article about elastic layouts. The best I could do was a quick email between work. I always meant to come good on that. Thanks for asking; sorry it took so long.

    Also available in:

    1. Italiano
    2. Deutsch
    3. Español
    4. Russian

    This article will walk you through creating a basic elastic layout; what exactly an “em” is and how to calculate them, how to use ems to create an elastic layer for content with scalable text and images, including basic vertical rhythm.

    What is an Elastic Layout?

    An elastic layout scales with users’ text size.

    More accurately, an elastic interface scales with browser text size—commonly a default of 16px—which users can change if they wish. Some people make a permanent change for accessibility reasons, others use the UI controls to increase text size if they need to.

    Elastic design uses em values for all elements. Ems are a relative size, written like this: 1em, 0.5em, 1.5em etc. Ems can be specified to three decimal places like so: 1.063em. “Relative” means:

    1. They are calculated based on the font size of the parent element. E.g. If a <div> has a computed font size of 16px then any element inside that layer —a child— inherits the same font size unless it is changed. If the child font size is changed to 0.75em then the computed size would be 0.75 × 16px = 12px.
    2. If the user increases (or decreases) text size in their browser, the whole interface stretches (or shrinks.)

    See the elastic layout example. Adjust text size to see it scale. It contains all the CSS and HTML used in this tutorial.

    For other live elastic examples, visit Dan Cederholm’s beautiful and elastic SimpleBits, or resize text on this site.

    Elastic interfaces are flexible and accessible for users, and can be almost as precise as pixels for designers. Layouts can be created accurately and quickly using CSS once we grasp the basic relationship between font size, pixels and ems.

    Introducing Em, the Elastigirl of CSS

    The em is as powerful and flexible as Elastigirl, she doesn’t mind what the font size is, whether 12px, 16 or 60, she will always be exactly equal to it.

    The em is a unit of measurement in typography. What is it and how did it get its name? Here’s a little history:

    An em was originally equal to the size of the metal block used to cut a single letter of type for a specific font. It was roughly equivalent to the width of a capital letter “M”.

    Those with designers’ eyes amongst you might be saying, “hold up a second, letters don’t take up equal space.” You’d be right: Computers use kerning to adjust the horizontal space each letter occupies on the screen, making them equidistant and balanced. Originally, the metal block was trimmed or “kerned” to make the horizontal padding around each letter the same.

    So, in CSS, an em is actually a vertical measurement. One em equals the vertical space needed for any given letter in a font, regardless of the horizontal space it occupies. Therefore:

    If the font size is 16px, then 1em = 16px.

    Getting Started

    Before we start throwing ems around a stylesheet, we need to know what the default font size is in the browser. Luckily, we do:

    All popular browsers have a default font size of 16px. Therefore, at the default browser setting, 1em = 16px.

    In Firefox, you can check default font size via Tools > Options > Content.

    So, before a single CSS selector is written, the browser has a 16px deafult font size. The <body> inherits it unless styled otherwise using CSS. Therefore 1em = 16px, 0.5em = 8px, 10em = 160px and so on. We can now specify any element size we need to using ems!

    Setting Body Font Size

    Some erudite folks suggest setting the <body> font size to either the required font size for body text, or the equivalent of 10px (0.625em or 62.5%) to make calculating child lengths easier. Both have merit, but it seems more logical to me to leave it at the browser default and change it for child elements if necessary.

    So, we know that the body font size will be 16px by default. We also know that if a person has changed their settings, our elastic interface will not break, but adjust. Perfect, so we can set:

    body{ font-size:1em; }
    

    However, (gasp) IE has a problem with ems. Resizing text from medium (default) to large in IE5/6 would lead to a huge increase in font size rather than the gradual one expected. So another selector is needed to get IE to behave:

    html{ font-size:100%; }
    

    As Patrick H. Lauke previously pointed out, it’s an IE correction, not a hack—it doesn’t rely on a browser bug to work.

    IE will now behave and resize text gracefully, rather than in mighty leaps of stupefying grandeur.

    Let’s give our <body> some more style, and center everything in the viewport (this will be important later for our content wrapper.) Our initial CSS ends up like this:

    html{
    font-size: 100%;
    } 
    
    body{
    font-size: 1em;
    font-family: georgia, serif;
    text-align: center;
    color: #444;
    background: #e6e6e6;
    padding: 0;
    margin: 0;
    }
    

    Formula to Convert Pixels to ems

    When first creating elastic pages, you will find yourself doing calculations a lot. Keep a calculator handy.

    Tip: Find font size for any element with Chris Pederick’s brilliant Web developer toolbar using: Information > Display element information.

    I am no maths wizard, so I needed a simple formula to remember. As a designer, I know pixels intimately, so that’s where I start. I calculate what 1px is in ems and multiple by the pixel size I need. That gives me the equivalent em value. We know that 1em is always equal to the font size of the parent element, therefore:

    1 ÷ parent font-size × required pixel value = em value

    For your bookmarks: Pixel to ems conversion table for font sizes.

    Don’t let my talk of forumla put you off. Elastic interfaces are a joy to build so let’s get practical and create some page elements.

    Building an Elastic Container: The Supersuit

    To create the centred content layer in the example, we need a little HTML. Let’s be really imaginative and give it an ID of “wrap”:

    <div id="wrap">
    …
    </div>
    

    We want it to be 740px wide to comfortably fit an 800×600px viewport like the example. What is 740px in ems? Let’s find out:

    1. Set a 740px width in ems for our layer:

      We know that the parent element (<body>) has a font size of 16px. Our child layer (<div id="wrap">) will inherit it. So we can calculate what 1px is in ems:

      1em = 16px. Therefore, 1px = 1 ÷ 16 = 0.0625em.

      Ems allow only three decimal places. More is fine in calculations but before writing CSS, round it up to three.

      Then multiply by 740 to get ems:

      0.0625em × 740 = 46.25em

      Or do the whole calculation in one go with the formula:

      1 ÷ 16 × 740 = 46.25em

      (1 ÷ parent font-size × required pixel value = em value)

      You can use the same formula to calculate ems for any width or height you need. Find 1px is in ems for that element. Multiple that by the pixel value you require to get the em equivalent.

    2. Create CSS:

      Apply the width in ems, center the layer in the viewport using the auto left and right margins, give it a 1px gray border with a white background and align the text left:

      #wrap{
      width: 46.25em;
      margin: 1.5em auto;
      border: 0.063em solid #ccc;
      background: #fff;
      text-align: left;
      }
      

    Now we have an elastic wrapper for our content!

    Styling Text with ems

    Let’s insert a <h1> and a <p> to our wrapper like so:

    <div id="wrap">
    
    <h1> … <h1>
    <p> … <p>
    
    </div>
    

    Essential reading:

    The Elements of Typographic Style applied to the Web created by Richard Rutter based on the masterwork by Robert Bringhurst.

    While we're here, we might as well add some typographic goodness by selecting a basic leading and adding some vertical rhythm, with everything expressed in ems. Here’s a little more history:

    Leading (pronounced “led–ing”) was traditionally the insertion of lines of lead underneath rows of text. It is expressed in CSS as line-height but instead of adding space below, it increases the space above and below each line of text.

    In the example, I’ve used the same font sizes as Richard Rutter did in his outstanding chapter on vertical motion to make your reading as consistent as possible. The heading font size will be 18px. The paragraph font size will be 12px with an 18px line height. 18px will be our basic leading—the most important value for our interface. Everything else will be proportional to that.

    A note on CSS inheritance: Our content wrapper, <div id="wrap">, has no font size set so it has inherited the 1em (16px) font size from its parent, the <body>. Any elements within our wrapper will also inherit that font size, unless we tell the browser otherwise, as we’re about to do.

    1. Set a 12px font size with 18px line height and margin for paragraphs:

      We know that our paragraphs have inherited a 1em (16px) font size from its parent, <div id="wrap">. From our previous calculation, we already know that 1px is 0.0625em. We simply multiple that by 12 to get the em value for 12px:

      0.0625 × 12 = 0.750em

      Or do the whole calculation in one go with the formula:

      1 ÷ 16 × 12 = 0.750em

      (1 ÷ parent font-size × required pixel value = em value)

      Then apply that to the CSS:

      p{
      font-size: 0.750em;
      }
      

      Margin, line height, padding etc. in ems are all relative to the font size of the element they belong to.

      To calculate the desired line height and margin of 18px for our basic leading we do the following:

      18 ÷ 12 = 1.5em

      Dividing the desired line height (18px) by the element font size (12px) gives us the em value for line height. In this example, the line height is 1 and a half times the font size: 1.5em.

      Add line height and margin properties to the CSS:

      p{
      font-size: 0.750em;
      line-height: 1.5em;
      margin: 1.5em;
      }
      

      Now the browser will say to itself, “Oh, line height and margin is set to 1.5em, so that should be 1.5 times the font size. What’s the font size, again? 12px? OK, cool, make line height and margin 1.5 times that, so 18px.” It will do all that faster than Dash too, and render it. Wow.

    2. Set 18px font size for the <h1>:

      The <h1> has inherited a 1em (16px) font size from it’s parent, <div id="wrap">. So, we already know what 1px is from before: 0.0625em. We simply multiple that by 18 to get the em value for 18px:

      0.0625 × 18 = 1.125em

      Or do the whole calculation in one go with the formula:

      1 ÷ 16 × 18 = 1.125em

      (1 ÷ parent font-size × required pixel value = em value)

      Then apply that to the CSS:

      h1{
      font-size: 1.125em;
      }
      

      To retain our vertical rhythm we want to set an 18px line height and margin. Easy: If the font size is 18px then 18px in ems is 1em! Let’s add the properties to the CSS (and make the font weight light:)

      h1{
      font-size: 1.125em;
      line-height: 1em;
      margin: 1em;
      font-weight: 300;
      }
      

    We now have vertical rhythm! Let’s move on to images.

    Sizing Images in ems

    To retain the rhythm of the the example page, the size of an image should be a multiple of the basic leading.

    Our image has a width and height of 90px (18px × 5.) It has right and bottom margins of 18px and is floated left in the paragraph text. This is the HTML:

    <p>
    <img src="90.jpg" alt="Clevedon Pier" /> Lorem…
    </p>
    

    The image is a child of the paragraph—it’s parent—so we know that the image has inherited a font size of 12px. Therefore, to calculate the image width and height we do the following using the formula:

    1 ÷ 12 × 90 = 7.5em

    (1 ÷ parent font-size × required pixel value = em value)

    Then apply that to the CSS:

    p img{
    width: 7.5em;
    height: 7.5em;
    }
    

    We already know what 18px is in ems for the parent paragraph, so let’s add the margin property (and the float) to the CSS:

    p img{
    width: 7.5em;
    height: 7.5em;
    margin: 0 1.5em 1.5em 0;
    float: left;
    }
    

    N.B. The image does not need to be within a paragraph to give it semantic meaning. The was used in this instance as an example of how to take inheritance into account whilst calculating ems.

    Now we have a supersuit elastic container with some elastic content and vertical rhythm like the example. With a bit of a luck, you have a better insight into creating elastic layouts, and designing with ems in particular. We’re done, you’re the Edna Mode of designers! The elastic example page has all the HTML and CSS you need. View source to grab it.

    Using Elastic Design

    Some of the benefits of elastic design for designers are precision, control and accessibility. However, some people have expressed concerns that allowing the content to expand past the edge of the viewport at larger text sizes could be problematic. Also, text will sometimes wrap and flow within the framework when the text size is changed; a minor issue, but worth noting.

    Concerns have also been expressed over the loss of image fidelity at increased text size. However, if a person changes their text size, the chances are they will also benefit from larger images, and browsers get better at resizing images as they increase in size. Hopefully browsers will get even better at resizing, or maybe we’ll soon have SVG and scalable background images to use.

    Implementing elastic design can deliver a deep understanding of ems in CSS. It definitely has a place in every designer or developer’s toolkit, whether in combination with other techniques in hybrid layouts or on its own.

    And finally…

    Any omissions or errors in this article are my own, so please let me know if I’ve missed something. If you know of other good and relevant resources elsewhere, please add them to the comments or email me and I’ll include them.

    I also take full responsibility for all refences to The Incredibles—my 2 sons gave kind permission for me to use their figures for the title image—and I hope Elastigirl doesn’t mind being compared to the em unit.

    References and Further Reading

    1. Resources:
      1. Elastic layout example (from the article)
      2. Reference table of common pixel font sizes and em equivalents
    2. Further reading:
      1. The amazing em unit
      2. Em discussion on Typophile
      3. The Elements of Typographic Style applied to the Web — Richard Rutter
      4. CSS2: Font size
      5. CSS2: Assigning property values, Cascading, and Inheritance
      6. CSS Layouts: The Fixed. The Fluid. The Elastic. — Mike Cherim
      7. Fixed or fluid width? Elastic! — Roger Johansson
      8. Elastic Design — A List Apart

    Can you Translate?

    Also, translated into Italiano by Nicola Pressi, and Deutsch by Pascal Birchler.

    If you are bilingual and would like to translate this article for non English speakers, please download my vCard via the about page and contact me. Thanks!

    Share

  10. An Ode to Exersize Book Margins

    Remember your old school exersize books? If you went to school in the UK, you’ll probably remember the margins, with a red or grey vertical line giving the page a little elbow room (and trying to make your writing line up.)

    Mine would end up full of all sorts of things: Numerous red “Sp” spelling reminders from the teacher (nothing᾿s changed you’ll note), with oft–begrudged marks of “7/10”, as well as my own art, in the loosest sense of the word. That would include snippets of ubiquitous bubble writing; predictably inspired by the girls who seemed to love it—and anyone who could do it well—even more than Wotsits or Cabbage Patch Kids. There would be various malformed “Chad” and Fido Dido sketches (inspired by 7-Up ads in Singapore when I was younger,) and carefully crafted reproductions of Biffa Bacon next to attempts at rendering male reproductive anatomy. Banksy wasn’t even a twinkle in his mummy’s eye at that point, and anyway, Chad and mutated willys were easier to draw than teddybears with Molotov cocktails.

    Therefore, I decided to resurrect the exersize book margin in my print stylesheet. It’s still a little messy and very verbose and will, no doubt, be massaged into pedantic cleanliness over time. The stylesheet, that is, not the margin.

    Asides and small pictures are pulled into the margin where they belong, leaving you bags of room for your own notes, doodles and experiments in anatomical drawings of the male reproductive organ. Ah, but if only browsers would respect orphans, page-break-after:avoid, page-break-inside:avoid and other useful print CSS, but that is a tale for another day. Do a print preview to take a peek. Perhaps the best margin art™ should win a prize—what was in yours all those years ago?

    Share