Mozilla

CSS Articles

Sort by:

View:

  1. Web Open Font Format for Firefox 3.6

    This article was written by John Daggett. John is a Mozilla contributor and has been working hard with font creators and web developers to improve the state of fonts on the web. This article is a high-level overview of whats different and shows some examples of WOFF in use. A full list of other supporting organizations can be found at the official Mozilla Blog.

    In Firefox 3.5 we included support for linking to TrueType and OpenType fonts. In Firefox 3.6 we’re including support for a new font format – the Web Open Font Format, or WOFF. This format has two main advantages over raw TrueType or OpenType fonts.

    1. It is compressed, which means that you will typically see much smaller download sizes compared with raw TrueType or OpenType fonts.
    2. It contains information that allows you to see where the font came from – without DRM or labeling for a specific domain – which means it has support from a large number of font creators and font foundries.

    The WOFF format originated from a collabaration between the font designers Erik van Blokland and Tal Leming with help from Mozilla’s Jonathan Kew. Each had proposed their own format and WOFF represents a melding of these different proposals. The format itself is intended to be a simple repackaging of OpenType or TrueType font data, it doesn’t introduce any new behavior, alter the @font-face linking mechanism or affect the way fonts are rendered. Many font vendors have expressed support for this new format so the hope is this will open up a wider range of font options for web designers.

    Details on Differences between TrueType, OpenType and WOFF

    First, compression is part of the WOFF format so web authors can optimize the size of fonts used on their pages. The compression format is lossless, the uncompressed font data will match that of the original OpenType or TrueType font, so the way the font renders will be the same as the original. Similar compression can be achieved using general HTTP compression but because compression is part of the WOFF format, it’s simpler for authors to use, especially in situations where access to server configuration is not possible.

    Second, the format includes optional metadata so that a font vendor can tag their fonts with information related to font usage. This metadata doesn’t affect how fonts are loaded but tools can use this information to identify the source of a given font, so that those interested in the design of a given page can track down the fonts used on that page. Fonts in WOFF format are compressed but are not encrypted, the format should not be viewed as a “secure” format by those looking for a mechanism to strictly regulate and control font use.

    Note: until Firefox 3.6 ships, users can test the use of WOFF fonts with Firefox nightly builds.

    Examples

    Below is a simple example that shows how to construct an @font-face rule that links to a WOFF font. To support browsers that only support direct linking to OpenType and TrueType fonts, the ‘src’ descriptor lists the WOFF font first along with a format hint (“woff”), followed by the TrueType version:

    /* Gentium (SIL International) */
     
    @font-face {
      font-family: GentiumTest;
      src: url(fonts/GenR102.woff) format("woff"),
           url(fonts/GenR102.ttf) format("truetype");
    }
     
    body {
      font-family: GentiumTest, Times, Times New Roman, serif;
    }

    Structured this way, browsers that support the WOFF format will download the WOFF file. Other browsers that support @font-face but don’t yet support the WOFF format will use the TrueType version. (Note: IE support is a bit trickier, as discussed below). As WOFF is adopted more widely the need to include links to multiple font formats will diminish.

    Other examples below demostrate the use of WOFF formatted fonts but each example has been constructed so that it will work in any browser that supports @font-face, including Internet Explorer.

    A font family with multiple faces

    Using a Postscript CFF font

    African Language Display

    Below is an example of how downloadable fonts can be used to render languages for which font support is usually lacking. The example shows the UN Declaration of Human Rights, translated into two African languages, and how these render with default browser fonts vs. with a downloadable font suited for rendering these languages.

    Note that in one of these examples that the font size goes from a 3.1MB TTF to a 1MB WOFF font and in the other from a 172KB TTF to an 80KB WOFF file.

    Another Postscript CFF font

    An example in Japanese

    Working With Other Browsers

    Firefox 3.6 will be the first shipping browser to support the WOFF format so it’s important to construct @font-face rules that work with browsers lacking WOFF support. One thing that helps greatly with this is the use of format hints to indicate the format of font data before it’s downloaded; browsers that don’t recognize a given format simply skip data in a format they don’t support.

    Internet Explorer, including IE8, only supports the EOT font format and only implements a subset of the @font-face rule descriptors. This makes creating cross-platform @font-face rules that work with IE especially tricky. One solution is to make different rules for IE:

    @font-face {
      font-family: GentiumTest;
      src: url(fonts/GenR102.eot);  /* for IE */
    }
     
    @font-face {
      font-family: GentiumTest;
      /* Works only in WOFF-enabled browsers */
      src: url(fonts/GenR102.woff) format("woff");
    }

    One minor downside of this is that IE doesn’t understand format hints and doesn’t parse @font-face URL’s correctly, it treats format hints as part of the URL, so web authors using the @font-face rules above will see the following in their access logs:

    GET /fonts/GenR102.eot HTTP/1.1" 200 303536
    GET /fonts/GenR102.woff)%20format(%22woff%22) HTTP/1.1" 404 335

    IE successfully pulls down and uses the EOT version of the font but also tries to pull down the WOFF font with the format hint included in the URL. This fails and doesn’t affecting page rendering but it wastes valuable server resources. For more discussion, see Paul Irish’s blog post for one interesting workaround.

    Another problem is that IE currently tries to download all fonts on the page, whether they are used or not. That makes site-wide stylesheets containing all fonts used on site pages difficult, since IE will always try to download all fonts defined in @font-face rules, wasting lots of server bandwidth.

    Further Resources

    Documentation

    Latest draft WOFF specification
    Original blog post on using @font-face
    CSS3 Fonts working draft
    MDC @font-face documentation

    Tools

    Jonathan Kew’s sample encoding/decoding code
    woffTools – tools for examining and validating WOFF files
    FontTools/TTX – Python library and tool for manipulating font data
    Web-based font subsetting tool

    General @font-face Examples

    CSS @ Ten: The Next Big Thing
    Example layout using Graublau Sans
    Examples of Interesting Web Typography
    The Elements of Typographic Style Applied to the Web

    Font Resources

    Font Squirrel
    10 Great Free Fonts for @font-face
    40 Excellent Free Fonts by Smashing Magazine

  2. beautiful fonts with @font-face

    This article is also available in Bulgarian.

    While Firefox 3.0 improved typographic rendering by introducing support for kerning, ligatures, and multiple weights along with support for rendering complex scripts, authors are still limited to using commonly available fonts in their designs. Firefox 3.5 removes this restriction by introducing support for the CSS @font-face rule, a way of linking to TrueType and OpenType fonts just as code and images are linked to today. Safari has supported this type of font linking since version 3.1, and Opera has announced that they plan to support it in Opera 10.

    Using @font-face for font linking is relatively straightforward. Within a stylesheet, each @font-face rule defines a family name to be used, the font resource to be loaded, and the style characteristics of a given face such as whether it’s bold or italic. Firefox 3.5 only downloads the fonts as needed, so a stylesheet can list a whole set of fonts of which only a select few will actually be used.

    /* Graublau Sans Web (www.fonts.info) */
     
    @font-face {
      font-family: Graublau Sans Web;
      src: url(GraublauWeb.otf) format("opentype");
    }
     
    body {
      font-family: Graublau Sans Web, Lucida Grande, sans-serif;
    }

    Browsers that support @font-face will render text using Graublau Sans Web while older browsers will render text using either Lucida Grande or the default sans-serif face. Example here:



    Digging A Little Deeper

    Most font families today consist of only four faces: regular, bold, italic and bold italic. To define each of these faces the font-weight and font-style descriptors are used. These define the style of the face; there’s no concept of a cascade or inheritance that applies here. Without an explicit definition each of these defaults to a value of ‘normal':

    /* Gentium by SIL International   */
    /* http://scripts.sil.org/gentium */
     
    @font-face {
      font-family: Gentium;
      src: url(Gentium.ttf);
      /* font-weight, font-style ==> default to normal */
    }
     
    @font-face {
      font-family: Gentium;
      src: url(GentiumItalic.ttf);
      font-style: italic;
    }
     
    body { font-family: Gentium, Times New Roman, serif; }

    The sample text below when rendered with this font family:



    A feature that’s easy to overlook is that @font-face allows the creation of families with more than just regular and bold faces — up to nine weights can be defined for a single family. This is true even on Windows, where underlying platform limitations usually restrict font families to just regular and bold weights. Fonts such as those of the Japanese open source M+ Fonts project have as many as seven weights. A selection of these are used in the sample below:



    In some situations, authors may prefer to use fonts available locally and only download fonts when those faces aren’t available. This is possible with the use of local() in the definition of the src descriptor of an @font-face rule. The browser will iterate over the list of fonts in the src descriptor until it successfully loads one.

    /* MgOpen Moderna                      */
    /* http://www.zvr.gr/typo/mgopen/index */
     
    @font-face {
      font-family: MyHelvetica;
      src: local("Helvetica Neue"),
           local("HelveticaNeue"),
           url(MgOpenModernaRegular.ttf);
    }
     
    @font-face {
      font-family: MyHelvetica;
      src: local("Helvetica Neue Bold"),
           local("HelveticaNeue-Bold"),
           url(MgOpenModernaBold.ttf);
      font-weight: bold;
    }
     
    body { font-family: MyHelvetica, sans-serif; }

    The screenshot below shows from top to bottom the results on Mac OS X, Windows and Linux for a simple testcase that uses the font family defined above:



    The Helvetica Neue font family is available on most Mac OS X systems but generally on neither Windows nor Linux machines. When the example here is rendered on Mac OS X, the local Helvetica Neue faces are used and no font is downloaded. Under Windows and Linux the attempt to load a local font fails and a substitute font — MgOpen Moderna — is downloaded and used instead. MgOpen Moderna is designed to be a substitute for Helvetica, so it renders similarly to Helvetica Neue. This way, an author can guarantee text appearance but avoid a font download when it’s unnecessary.

    The name used to refer to a specific font face is the full name for an individual font. Generally it’s the family name plus the style name (e.g. “Helvetica Bold”). Under Mac OS X, the name is listed in the information panel for a given face. Select a single face and choose ‘Show Font Info’ from the Preview menu in FontBook:

    Similar tools exist under Linux. On Windows, use the font properties extension, a free download from Microsoft to view these names. With the extension installed, the properties panel shows information about an individual font. The full name is referred to as the “Font Name” on the Name tab:

    Safari only supports PostScript name lookup under Mac OS X, so under Mac OS X Postscript names are also supported. For OpenType PS fonts (often labeled with an .otf extension) the full name is the same as the PostScript name under Windows. So for these fonts, authors are advised to include both the full name and the PostScript name for cross-platform interoperability.

    Supporting Many Languages

    Many languages suffer from a lack of commonly available fonts. For minority languages and ancient scripts, the options often dwindle to just a handful. The use of @font-face allows authors using these languages to ameliorate this by including fonts with their pages.

    @font-face {
      font-family: Scheherazade;
      src: url(fonts/ScheherazadeRegAAT.ttf) format("truetype-aat"),
           url(fonts/ScheherazadeRegOT.ttf) format("opentype");
    }
     
    body { font-family: Scheherazade, serif; }

    Languages such as Arabic require text shaping, where the display of a given character is affected by the characters surrounding it. Different platforms support different rendering technologies to enable text shaping; under Mac OS X, AAT fonts are required while under Windows and Linux OpenType fonts are required. Without a font in a format required for a given platform, text shaping will not be rendered correctly.



    Under Mac OS X, the AAT version of the font is downloaded. On Windows and Linux, where rendering with AAT fonts is not supported, the download of the AAT font is skipped and the OpenType font is used instead. Hence, the text is rendered correctly on all platforms.

    Cross-Site Font Usage

    By default, Firefox 3.5 only allows fonts to be loaded for pages served from the same site. This prevents sites from freely using fonts found on other sites. For sites that explicitly want to allow cross-site font sharing, an online font library for example, Firefox 3.5 supports the use of access control headers to control this behavior. By adding an additional header to the HTTP headers sent with font files, sites can enable cross-site usage.

    # example Apache .htaccess file to add access control header
     
    <filesMatch ".(ttf|otf)$">
    <ifModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
    </ifModule>
    </filesMatch>

    With this HTTP header enabled, any page can access the fonts on this site, not just pages from the same site.

    Font Licensing Issues

    When using a font for a website, it’s important to always confirm that the font license permits use on a website. If the license agreement is filled with opaque legalese, err on the side of caution and check with the font vendor before using a font on a site. If the license permits its use, it’s a good idea to add a comment near the @font-face rules that points to the license, for future reference.

    “I found a free font, can I use it on my site?”

    Maybe, maybe not. Some free fonts are distributed as teaser products to encourage a purchase and don’t allow for redistribution or posting on a web server. Check the license, even for free fonts.

    “I just want to use [insert favorite font name here] on my site. Is that possible?”

    Right now, probably not. The use of font linking on the web is still in its infancy. Most fonts that ship with proprietary OS’s today have licenses that limit their use to standard desktop applications, so uploading these fonts to a web server is almost certainly not permitted. Piracy has plagued the font industry in the past, so most font vendors are wary of allowing their fonts to be used except in relatively limited contexts. Many font vendors are focused on the needs of publishing and printing industries, and the relative complexity of their license agreements often reflects this. In the future, some font designers may conclude that the sales of fonts as web fonts will outweigh any potential loss in sales due to piracy, others may not. Their license agreements will reflect this choice and should be respected.

    The stock photography market is often described as a $2 billion market but the web font market is still close to a $0 market, it can only go up!

    Font Linking In Internet Explorer

    Font linking has been possible with Internet Explorer but only for linking to fonts in the proprietary EOT font format. The only way to create EOT fonts is to use the Microsoft WEFT tool, available only on Windows. Only TrueType and OpenType TT fonts can be converted to EOT format, OpenType PS (.otf) fonts cannot be used.

    Internet Explorer only recognizes the font-family and src descriptors within @font-face rules, so each family can only contain a single face. It doesn’t understand format() hints and will ignore any @font-face rule containing these hints. This behavior can be used enable font linking cross platform:

    /* Font definition for Internet Explorer */
    /*         (*must* be first)             */
    @font-face {
      font-family: Gentium;
      src: url(Gentium.eot) /* can't use format() */;
    }
     
    /* Font definition for other browsers */
    @font-face {
      font-family: Gentium;
      src: url(Gentium.ttf) format("opentype");
    }

    Future Work

    For Firefox 3.5, the font-stretch and unicode-range descriptors are not supported. Fonts defined in SVG documents are also not supported yet. These are under consideration for inclusion in future releases. As always, patches are welcome!

    Further Resources

    Translations

    Documentation

    Examples

    Font Resources

    Font Politics

  3. privacy-related changes coming to CSS :visited

    For more information about this, have a look at David Baron’s post, the bug and the post on the security blog.

    For many years the CSS :visited selector has been a vector for querying a user’s history. It’s not particularly dangerous by itself, but when it’s combined with getComputedStyle() in JavaScript it means that someone can walk through your history and figure out where you’ve been. And quickly – some tests show the ability to test 210,000 URLs per minute. At that rate, it’s possible to brute force a lot of your history or at least establish your identity through fingerprinting. Given that browsers often keep history for a long time it can reveal quite a bit about where you’ve been on the web.

    At Mozilla we’re serious about protecting people’s privacy, so we’re going to fix this problem for our users. To do so we’re making changes to how :visited works in Firefox. We’re not sure what release this will be part of yet and the fixes are still making their way through code review, but we wanted to give a heads up to people as soon as we understood how we wanted to approach fixing this.

    These changes will have some impact on web sites and developers, so you should be aware of them. At a high level here’s what’s changing:

    • getComputedStyle (and similar functions like querySelector) will lie. They will always return values as if a user has never visited a site.
    • You will still be able to visually style visited links, but you’re severely limited in what you can use. We’re limiting the CSS properties that can be used to style visited links to color, background-color, border-*-color, and outline-color and the color parts of the fill and stroke properties. For any other parts of the style for visited links, the style for unvisited links is used instead. In addition, for the list of properties you can change above, you won’t be able to set rgba() or hsla() colors or transparent on them.

    These are pretty obvious cases that are used widely. There are a couple of subtle changes to how selectors work as well:

    • If you use a sibling selector (combinator) like :visited + span then the span will be styled as if the link were unvisited.
    • If you’re using nested link elements (rare) and the element being matched is different than the link whose presence in history is being tested, then the element will be drawn as if the link were unvisited as well.

    These last two are somewhat confusing, and we’ll have examples of them up in a separate post.

    The impact on web developers here should be minimal, and that’s part of our intent. But there are a couple of areas that will likely require changes to sites:

    • If you’re using background images to style links and indicate if they are visited, that will no longer work.
    • We won’t support CSS Transitions that related to visitedness. There isn’t that much CSS Transition content on the web, so this is unlikely to affect very many people, but it’s still worth noting as another vector we won’t support.

    We’d like to hear more about how you’re using CSS :visited and what the impact will be on your site. If you see something that’s going to cause something to break, we’d like to at least get it documented. Please leave a comment here with more information so others can see it as well.

  4. color correction for images in Firefox 3.5

    Back in Firefox 3, we introduced support for color profiles in tagged images, but it was disabled by default. In Firefox 3.5 we were able to make the color correction process about 5x faster than it was in Firefox 3 so we’ve enabled support for color correction for tagged images.

    Most images on the web are untagged. If you don’t know the difference between tagged images and untagged images the odds are good are you won’t notice this change. However, we suggest that you read on to learn about what it might mean for you if you want to include them and how future Firefox releases might change the interactions between CSS colors and images.

    What’s a color profile?

    People who spend a lot of time taking photographs or any kind of high-resolution color printing will understand that many output devices – LCDs, CRTs, paper etc – all have very different interpretations of what various colors mean. For example, uncorrected red will look very different on an LCD vs. a CRT. You can see this if you set up two very different monitors next to each other and the operating system doesn’t do color correction – colors will look more washed out in one of them vs. the other.

    JPG and PNG images both have support for color profiles. These color profiles allow Firefox to take colors in the image and translate them into colors that are independent of any particular device.

    While images contain color profiles it’s also important to note that output devices like monitors also have color profiles. As an example an output device may be better at displaying reds than blues. When you’re getting ready to show something that’s “red” on that device it might need to be converted from the neutral #ff0000 value to #f40301 in order to show up as red on the screen.

    What this means is that there are actually two conversions that take place with color profiles. The first is to take the original color information in the image and, using the color profile, convert it into a device-independent color space. Then once it’s in that independent space you convert it again using the output device’s color profile to get it ready to display on the output device.

    So what about CSS colors?

    It’s important to understand how color profiles work and how they are converted to properly understand how CSS interacts with these color spaces.

    In Firefox 3.5 we consider CSS colors to already be in the device output’s color space. Another way of saying this is that CSS colors are not in the neutral color space and are not converted into the output device like tagged images are.

    What this means is that if you have a tagged image where a color is expected to match the CSS that’s right next to it, it won’t. Or at least it’s likely that it won’t on some output device – maybe not the one that you happen to be using for development. Remember that different output devices have different color profiles. Here’s an example of what that looks like:

    In Firefox 3, this will look like one contiguous block of purple. In Firefox 3.5 and Safari you will notice that there’s a purple box within a purple box (unless your system profile is sRGB.) This is because the image is color corrected while the surrounding CSS is not.

    This is where the statement about the future comes in. In a future release of Firefox we are likely to make it possible for people to turn on color correction for tagged images and CSS. You can test this setting today by changing the pref listed on the page on color correction on the Mozilla Developer Center to “Full color management.” In that case untagged images should continue to work as we will be rendering both CSS and untagged images in the sRGB color space.

    Image support and tools

    PNG’s can be tagged in three different ways. First they can have an iCCP chunk that contains the associated ICC profile. Second they can be explicitly tagged as sRGB using a sRGB chunk. Finally, they can contain gAMA and cHRM chunks that describe the image’s gamma and chromaticies. Using any of thse methods will cause Firefox to color correct the image.

    You can remove all of the color correction chunks resulting in an untagged image using pngcrush:

    pngcrush -rem gAMA -rem cHRM -rem iCCP -rem sRGB infile.png outfile.png

    Alternatively, you can use TweakPNG and delete the gAMA, cHRM, iCCP and sRGB chunks by hand.

  5. Firefox 5 is here

    Today, three months after the release of Firefox 4, we release Firefox 5, thanks to our new development cycle. Developers will be able to create richer animations using CSS3 Animations. This release comes with various improvements, performance optimization and bug fixes.

    CSS3 Animations

    CSS Animations (check out the documentation) are a new way to create animations using CSS. Like CSS Transitions, they are efficient and run smoothly (see David Baron’s article), and the developers have a better controls over the intermediate steps (keyframes), and can now create much more complex animations.

    Notable changes

    Other Bug Fixes and Performance Improvements:

    HTML

    Canvas improvements

    • The <canvas> 2D drawing context now supports specifying an ImageData object as the input to the createImageData() method; this creates a new ImageData object initialized with the same dimensions as the specified object, but still with all pixels preset to transparent black.
    • Specifying non-finite values when adding color stops through a call to the CanvasGradient method addColorStop() now correctly throws INDEX_SIZE_ERR instead of SYNTAX_ERR.
    • The HTMLCanvasElement method toDataURL() now correctly lower-cases the specified MIME type before matching.
    • getImageData() now correctly accepts rectangles that extend beyond the bounds of the canvas; pixels outside the canvas are returned as transparent black.
    • drawImage() and createImageData() now handle negative arguments in accordance with the specification, by flipping the rectangle around the appropriate axis.
    • Specifying non-finite values when calling createImageData() now properly throws a NOT_SUPPORTED_ERR exception.
    • createImageData() and getImageData() now correctly return at least one pixel’s worth of image data if a rectangle smaller than one pixel is specified.
    • Specifying a negative radius when calling createRadialGradient() now correctly throws INDEX_SIZE_ERR.
    • Specifying a null or undefined image when calling createPattern() or drawImage() now correctly throws a TYPE_MISMATCH_ERR exception.
    • Specifying invalid values for globalAlpha no longer throws a SYNTAX_ERR exception; these are now correctly silently ignored.
    • Specifying invalid values when calling translate(), transform(), rect(), clearRect(), fillRect(), strokeRect(), lineTo(), moveTo(), quadraticCurveTo(), or arc() no longer throws an exception; these calls are now correctly silently ignored.
    • Setting the value of shadowOffsetX, shadowOffsetY, or shadowBlur to an invalid value is now silently ignored.
    • Setting the value of rotate or scale to an invalid value is now silently ignored.

    CSS

    • Support for CSS animations has been added, using the -moz- prefix for now.

    DOM

    • The selection object’s modify() method has been changed so that the “word” selection granularity no longer includes trailing spaces; this makes it more consistent across platforms and matches the behavior of WebKit’s implementation.
    • The window.setTimeout() method now clamps to send no more than one timeout per second in inactive tabs. In addition, it now clamps nested timeouts to the smallest value allowed by the HTML5 specification: 4 ms (instead of the 10 ms it used to clamp to).
    • Similarly, the window.setInterval() method now clamps to no more than one interval per second in inactive tabs.
    • XMLHttpRequest now supports the loadend event for progress listeners. This is sent after any transfer is finished (that is, after the abort, error, or load event). You can use this to handle any tasks that need to be performed regardless of success or failure of a transfer.
    • The Blob and, by extension, the File objects’ slice() method has been removed and replaced with a new, proposed syntax that makes it more consistent with Array.slice() and String.slice() methods in JavaScript. This method is named mozSlice() for now.
    • The value of window.navigator.language is now determined by looking at the value of the Accept-Language HTTP header.

    JavaScript

    • Regular expressions are no longer callable as if they were functions; this change has been made in concert with the WebKit team to ensure compatibility (see WebKit bug 28285).
    • The Function.prototype.isGenerator() method is now supported; this lets you determine if a function is a generator.

    SVG

    • The class SVG attribute can now be animated.
    • The following SVG-related DOM interfaces representing lists of objects are now indexable and can be accessed like arrays; in addition, they have a length property indicating the number of items in the lists: SVGLengthList , SVGNumberList , SVGPathSegList , and SVGPointList.

    HTTP

    • Firefox no longer sends the “Keep-Alive” HTTP header; we weren’t formatting it correctly, and it was redundant since we were also sending the Connection: or Proxy-Connection: header with the value “keep-alive” anyway.
    • The HTTP transaction model has been updated to be more intelligent about reusing connections in the persistent connection pool; instead of treating the pool as a FIFO queue, Necko now attempts to sort the pool with connections with the largest congestion window (CWND) first. This can reduce the round-trip time (RTT) of HTTP transactions by avoiding the need to grow connections’ windows in many cases.
    • Firefox now handles the Content-Disposition HTTP response header more effectively if both the filename and filename* parameters are provided; it looks through all provided names, using the filename* parameter if one is available, even if a filename parameter is included first. Previously, the first matching parameter would be used, thereby preventing a more appropriate name from being used. See bug 588781 .

    MathML

    Developer tools

    • The Web Console’s Console object now has a debug() method, which is an alias for its log() method; this improves compatibility with certain existing sites.

  6. Firefox 4: CSS3 calc()

    This article describes the CSS3 calc() value. This feature hasn’t landed yet in any Firefox tree but work to implement it is underway.

    Firefox will support the CSS calc() value, which lets you compute a length value using an arithmetic expression. This means you can use it to define the sizes of divs, the values of margins, the widths of borders, and so forth.

    Here is an example of a layout which would be tricky to setup without the calc() function:

    /*
    * Two divs aligned, split up by a 1em margin
    */
    #a {
      width:75%;
      margin-right: 1em;
    }
    #b {
      width: -moz-calc(25% - 1em);
    }

    This example makes sure an input text field won’t overlap its parent:

    input {
      padding:2px;
      border:1px solid black;
      display:block;
      width: -moz-calc(100% - 2 * 3px);
    }

    One particularly powerful feature of the calc() function that you can combine different units in the same computation:

    width: -moz-calc(3px + 50%/3 - 3em + 1rem);

    The current implementation supports the +, -, *, /, mod, min, and max operators.

    We’ll also support the min() and max() functions, which could be used like this:

    div {
      height: -moz-min(36pt, 2em);
      width: -moz-max(50%, 18px);
    }

    For more details, see:

  7. The CSS 3 Flexible Box Model

    This article about the Flexible Box Layout was written by Jérémie Patonnier, French open Web enthusiast.

    The flexible box model

    CSS 3 introduces a brand new box model in addition of the traditional box model from CSS 1 and 2. The flexible box model determines the way boxes are distributed inside other boxes and the way they share the available space.

    You can see the specification here.

    This box model is similar to the one used by XUL (the user interface language used by Firefox). Some others languages use similar box models such as XAML or GladeXML.

    Usually the flexible box model is exactly what you need if you want to create fluid layouts which adapt themselves to the size of the browser window or elastic layouts which adapt themselves to the font size.

    In this article, all my examples are based on the following HTML code:

    <body>
      <div id="box1">1</div>
      <div id="box2">2</div>
      <div id="box3">3</div>
    </body>

    Distributing boxes: so what?

    By default, the traditional CSS box model distributes boxes vertically depending on the HTML flow. With the flexible box model, it’s possible to specify the order explicitly. You can even reverse it. To switch to the flexible box model, set the property display to the value box (or inline-box) on a box which has child boxes.

    display: box;

    Horizontal or vertical distribution

    The box-orient property lets you specify the distribution axis. vertical and horizontal values define how boxes are displayed. Other values (inline-axis and block-axis) have the same effect, but also let you define the baseline alignment itself (basically the boxes are treated like “inline” boxes).

    body{
      display: box;
      box-orient: horizontal;
    }

    Reversed distribution

    The property box-direction allows you to set the order in which the boxes appear. By default–when you simply specify the distribution axis–the boxes follow the HTML flow and are distributed from top to bottom if you are using a vertical axis and from left to right if you are using a horizontal axis. By setting box-direction to reverse, you can reverse the boxes’ distribution order. It acts as if you actually reversed the order of the elements in the HTML.

    Be careful with this property because it changes the way some other properties work, which can produce some unexpected behavior.

    body {
      display: box;
      box-orient: vertical;
      box-direction: reverse;
    }

    Explicit distribution

    The property box-ordinal-group lets you specify the order in which the boxes will be distributed. This is the ultimate customization opportunity, because you can define the order you want, regardless of the HTML flow order. Those groups are defined by a number starting at 1 (which is the default value). So the box model will first distribute those groups, then all the boxes inside each group. The distribution occurs from the lowest value (the group numbered 1) to the highest (the groups numbered 2 and above).

    body {
      display: box;
      box-orient: vertical;
      box-direction : reverse;
    }
    #box1 {
      box-ordinal-group: 2;
    }
    #box2 {
      box-ordinal-group: 2;
    }
    #box3 {
      box-ordinal-group: 1;
    }

    And what about flexibility?

    If changing the natural HTML flow order is huge, the real fun begins when you start to deal with the available space.

    Box sizing

    By default, a box is not flexible. It becomes flexible only if it has the property box-flex with a value of at least 1.

    If a box is not flexible, it will be as wide as possible to make its content visible without any overflow. Its size can be forced with the properties width and height (or their min-*, and max-* alternatives).

    If a box is flexible, its size will be computed as follows:

    1. The explicit size declarations (width, height, min-* and max-*)
    2. The size of the parent box and all the remaining available inner space.

    So, if the boxes haven’t any size declarations, their sizes will fully depend on their parent box’s size. It will work like this: the size of box is equal to the size of its parent multiplied by the value of the its box-flex property divided by the sum of all the box-flex properties values of all boxes included in its parent.

    On the other hand, if one or more boxes have an explicit size statements, the size of all those boxes is computed and all the flexible boxes share the remaining available space on the same principle as above.

    It probably sounds a bit tricky, but with some examples it will become easier.

    All boxes are flexible

    In the next example, box 1 is twice the size of box 2 and box 2 has the same size as box 3. It looks the same as using percentages to set the boxes’ sizes. But there is a big difference. If you add a box, you don’t need to recalculate its size. With the flexible box model, each time you add a box, all the others automatically shrink to make room for the new one.

    body {
      display: box;
      box-orient: horizontal;
    }
    #box1 {
      box-flex: 2;
    }
    #box2 {
      box-flex: 1;
    }
    #box3 {
      box-flex: 1;
    }

    Some boxes have a fixed size

    In the next example, box 3, which is not flexible, is 160px in width. In this case, there’s 240px of free space available for boxes 1 and 2. So, box 1 will be 160px in width (240px x 2/3) and box 2 will be 80px in width (240px x 1/3). If you wish, you can make box 3 flexible as well. In this case the way the size of this box is computed will be almost the same as with the property min-width.

    body {
      display: box;
      box-orient: horizontal;
      width: 400px;
    }
    #box1 {
      box-flex: 2;
    }
    #box2 {
      box-flex: 1;
    }
    #box3 {
      width: 160px;
    }

    Managing overflow

    Because we can mix flexible boxes, inflexible boxes, and flexible boxes which have preset sizes, It’s possible for the sum of all the boxes’ sizes to be larger or smaller than the parent box size. So you can have too much space or not enough.

    I have too much space available; what do I do?

    The available space gets distributed depending on the properties box-align and box-pack

    The property box-pack manages the way the space is distributed on the horizontal axis and can have one of four possible values: start, end, justify, or center

    1. start: All the boxes are on the left side of the parent box and all the remaining space is on the right side.
    2. end: All the boxes are on the right and the remaining space is on the left
    3. justify: The available space is divided evenly in-between each boxes
    4. center: The available space is divided evenly on each side of the parent box

    The property box-align manages the way the space is distributed on the vertical axis and can have one of five values: start, end, center, baseline, and stretch

    1. start: The top edge of each box is placed along the top of the parent box and all the remaining space is placed below.
    2. end: The bottom edge of each box is placed along the bottom of the parent box and all the remaining space is placed above.
    3. center: The available space is divided evenly and placed half above and half below.
    4. baseline: All children are placed with their baselines aligned and the remaining space is placed before or after as necessary (This is a simplification about how this value really works, but you see the point).
    5. stretch: The height of each boxes is adjusted to fit the parent box height

    A warning about how those properties work: they are strongly influenced by the use of the properties box-orient and box-direction. They can cause some unexpected behavior (for example, the behavior of values start and end could be fully reversed). I hope that once the specification is finalized, we’ll have more information about how those properties work together.

    body {
      display: box;
      box-orient: horizontal;
      /* The content of the body is horizontally centered */
      box-pack: center;
      /* and vertically as well ... o/ */
      box-align: center;
      width: 100%;
      height : 100%;
    }

    What happens if I don’t have enough space?

    Just like with the traditional box model, the overflow property lets you to define the way it’s managed. No surprise here.

    However, you must be careful here too. Indeed, the use of the properties box-orient and box-direction can mess it up. For example, you can see elements overflowed to the right instead of the left or to the top instead of the bottom. Take the time to experiment before trying to use it on a big project or you could go mad.

    You can also avoid overflow by making the boxes run over multiple lines (or columns, depending on the orientation) by setting the property box-lines to multiple.

    Okay, cool, but does it work in real life?

    Yes it does! Both Gecko and WebKit have vendor-prefixed implementations of a box model (Note: The current state of the specification does not reflect Mozilla’s or WebKit’s implementation). This means that Firefox, Safari, Chrome, and any browsers that use one of those rendering engines are able to use the features described in this article. If you use one of those awesome browsers, here is a little demo of the flexible box model in action.

    If you’re not using a browser implementing a box model, this screenshot shows you what it looks like:

    To conclude

    You can start to use this box model to layout your HTML documents with modern web browsers. Be careful though, it’s the really first iteration of a W3C Working Draft. There will certainly be some changes. Anyway, the implementations available in Gecko and Webkit are extremely consistent and mature, so if there are changes, they should not be that troublesome.

    This box model is a very easy and simple way to solve some usual problems in web design (form layout, page footers, vertical centering, disassociation of visual flow from HTML flow, etc.). I strongly suggest you become familiar with it because it could become a standard tool for web designers in the near future (if Microsoft decides to include it in IE, it could become so very fast).

    What is already available is a good start to play with. But at this point, the way the traditional box model and the flexible box model interact is not very clear (for example, it’s impossible to use position:relative with the properties left or top on a box which uses the property box-ordinal-group). This will be improved, but don’t be surprised if your work habits are somewhat undermined. Another tricky point: the way all the properties relative to this new box model interact can be sometimes really confusing. This should remind you of the day you discovered the float property. ;)

    For further information

  8. Firefox – tons of tools for web developers!

    One of the goals of Firefox have always been to make the lives of web developers as easy and productive as possible, by providing tools and a very extensible web browser to enable people to create amazing things. The idea here is to list a lot of the tools and options available to you as web developers using Firefox.

    Continued…

  9. Firefox 4 Beta 2 is here – Welcome CSS3 transitions

    As we have explained before, Mozilla is now making more frequent updates to our beta program. So here it is, Firefox Beta 2 has just been released, 3 weeks after Beta 1.

    Firefox 4 Beta 1 already brought a large amount of new features (see the Beta 1 feature list). So what’s new for web developers in this beta?

    Performance & CSS3 Transitions

    The two major features for web developers with this release are Performance improvements and CSS3 Transitions on CSS3 Transforms.

    This video is hosted by Youtube and uses the HTML5 video tag if you have enabled it (see here). Youtube video here.

    Performance: In this new Beta, Firefox comes with a new page building mechanism: Retained Layers. This mechanism provides noticeable faster speed for web pages with dynamic content, and scrolling is much smoother. Also, we’re still experimenting with hardware acceleration: using the GPU to render and build some parts of the web page.

    CSS3 Transitions on transforms: The major change for web developers is probably CSS3 Transitions on CSS3 Transformations.

    CSS3 Transitions provide a way to animate changes to CSS properties, instead of having the changes take effect instantly. See the documentation for details.

    This feature was available in Firefox 4 Beta 1, but in this new Beta, you can use Transitions on Transformation.

    A CSS3 Transformation allows you to define a Transformation (scale, translate, skew) on any HTML element. And you can animate this transformation with the transitions.

    See this box? Move your mouse over it, and its position transform: rotate(5deg); will transform transform: rotate(350deg) scale(1.4) rotate(-30deg); through a smooth animation.
    #victim {
      background-color: yellow;
      color: black;
     
      transition-duration: 1s;
      transform: rotate(10deg);
     
      /* Prefixes */
     
      -moz-transition-duration: 1s;
      -moz-transform: rotate(5deg);
     
      -webkit-transition-duration: 1s;
      -webkit-transform: rotate(10deg);
     
      -o-transition-duration: 1s;
      -o-transform: rotate(10deg);
    }
    #victim:hover {
      background-color: red;
      color: white;
     
      transform:  rotate(350deg) scale(1.4) rotate(-30deg);
     
      /* Prefixes */
     
      -moz-transform:  rotate(350deg) scale(1.4) rotate(-30deg);
      -webkit-transform:  rotate(350deg) scale(1.4) rotate(-30deg);
      -o-transform:  rotate(350deg) scale(1.4) rotate(-30deg);
    }

    CSS 3 Transitions are supported by Webkit-based browsers (Safari and Chrome), Opera and now Firefox as well. Degradation (if not supported) is graceful (no animation, but the style is still applied). Therefore, you can start using it right away.

    Demos

    I’ve written a couple of demos to show both CSS3 Transitions on Transforms and hardware acceleration (See the video above for screencasts).

    This demo shows 5 videos. The videos are Black&White in the thumbnails (using a SVG Filter) and colorful when real size (click on them). The “whirly” effect is done with CSS Transitions. Move you mouse over the video, you’ll see a question mark (?) button. Click on it to have the details about the video and to see another SVG Filter applied (feGaussianBlur).
    This page shows 2 videos. The top left video is a round video (thanks to SVG clip-path) with SVG controls. The main video is clickable (magnifies the video). The text on top of the video is clickable as well, to send it to the background using CSS Transitions.
    This page is a simple list of images, video and canvas elements. Clicking on an element will apply a CSS Transform to the page itself with a transition. White elements are clickable (play video or bring a WebGL object). I encourage you to use a hardware accelerated and a WebGL capable browser. For Firefox on Windows, you should enable Direct2D.

    Credits

    Creative Commons videos:

    The multicolor cloud effect (MIT License)

  10. css gradients in Firefox 3.6

    Firefox 3.6 includes many CSS improvements. In this post we’re going to show you how to use CSS gradients.

    If you are running the latest beta of Firefox 3.6, you should check out our interactive demo and take a look at the corresponding code. Use the radio buttons to switch different style options on or off.

    Backgrounds with CSS Gradients

    Using CSS gradients in a background allows you to display smooth transitions between two or more specified colors without having to use images. This in turn reduces download time and bandwidth use, looks better while zooming, and lets you create a more flexible layout.

    Firefox 3.6 supports two kinds of CSS gradients: linear (-moz-linear-gradient) and radial (-moz-radial-gradient).

    Linear Gradients

    To create a linear gradient, you’ll need to set a starting point and a direction (or angle) for the gradient and to define the color stops.

     -moz-linear-gradient( [<point> || <angle>,]? <stop>, <stop> [, <stop>]* )

    Starting Point. The starting point works just like background position. You can set the horizontal and the vertical positions as a percentage, in pixels, or using left/center/right for horizontal, and top/center/bottom for vertical. Positions start from the top left corner. If you don’t specify the horizontal or the vertical position, it will default to center.

    For example, here’s a linear gradient that starts at the center (horizontal) and top (vertical), and goes from blue to white:

    basic_linear_bluetop

      .linear_gradient_square {
        width: 100px;
        height: 100px;
        border: 1px solid #333;
        background: -moz-linear-gradient(top, blue, white);
      }

    One that starts left (horizontal) and center (vertical):

    basic_linear_blueleft

        background: -moz-linear-gradient(left, blue, white);

    And a gradient starting left (horizontal) and top (vertical):

    basic_linear_bluetopleft

        background: -moz-linear-gradient(left top, blue, white);

    Angle. As you can see above, if you don’t specify an angle, it is defined automatically based on the start position. If you would like more control over the direction of the gradient, you can set the angle as well.

    For example, the following gradients have the same starting point of left center, but the one on the right hand-side also has an angle of 20 degrees.

    linear_gradient_angle

        background: -moz-linear-gradient(left 20deg, black, white);

    When specifying the angle, remember that is it the angle between a horizontal line and the gradient line, going counter-clockwise. So using 0deg will generate a left to right horizontal gradient, while 90deg will create a vertical gradient from the bottom to the top.

    linear_redangles

        background: -moz-linear-gradient(<angle>, red, white);

    Color Stops. In addition to start position and angle, you should specify color stops. Color stops are points along the gradient line that will have the specified color at the specified location (set as a percentage or length). The number of color stops is unlimited. If you use a percentage for the location, 0% represents the starting point, and 100% is the ending point, but values above and below those can be used to achieve the desired effect.

    Here’s a simple example with three color stops. Because no point is specified for the first and last colors, they will default to 0% and 100%.

    linear_colorstops

        background: -moz-linear-gradient(top, blue, white 80%, orange);

    Colors will be evenly spaced if no position is specified.

    linear_rainbow

        background: -moz-linear-gradient(left, red, orange, yellow, green, blue);

    Transparency. Gradients also support transparency. This can be useful, for example, when stacking multiple backgrounds. Here’s a combination of two backgrounds: one image and one linear gradient from white to transparent white.

    linear_multibg_transparent

    .multibackground_transparent {
        background: -moz-linear-gradient(right, rgba(255,255,255,0), rgba(255,255,255,1)), url(http://demos.hacks.mozilla.org/openweb/resources/images/patterns/flowers-pattern.jpg);
    }

    Radial Gradients

    The syntax for radial gradients is very similar to that of linear gradients:

     -moz-radial-gradient([<bg-position> || <angle>,]? [<shape> || <size>,]? <color-stop>, <color-stop>[, <color-stop>]*);

    In addition to the start position, the direction, and the colors, which you have already seen in linear gradients, radial gradients allow you to specify the gradient’s shape (circle or ellipse) and size (closest-side, closest-corner, farthest-side, farthest-corner, contain or cover).

    Color stops. Just like with linear gradients, you should define color stops along the gradient line. The following circles have the same color stops, but the gradient on the left defaults to evenly spaced colors, while the one on the right has a specific position for each color.

    radial_gradient_stop

     background: -moz-radial-gradient(red, yellow, #1E90FF);
     background: -moz-radial-gradient(red 5%, yellow 25%, #1E90FF 50%);

    Shape. Here you can see the difference between the two possible shapes, a circle (on the left) and an ellipse (on the right), both with a bottom left starting point:

    radial_circle_ellipse

     .radial_gradient_circle {
        background: -moz-radial-gradient(bottom left, circle, red, yellow, #1E90FF);
    }
     .radial_gradient_ellipse {
        background: -moz-radial-gradient(bottom left, ellipse, red, yellow, #1E90FF);
    }

    Size. The different options for size (closest-side, closest-corner, farthest-side, farthest-corner, contain or cover) refer to the point used to define the size of the circle or ellipse.

    Example: closest-side vs. farthest corner for an ellipse.
    The following two ellipses have different sizes. The one on the left is set by the distance from the start point (center) to the closest-side, while the one on the right is determined by the distance from the start point to the farthest corner.

    radial_ellipse_size

      background: -moz-radial-gradient(ellipse closest-side, red, yellow 10%, #1E90FF 50%, white);
      background: -moz-radial-gradient(ellipse farthest-corner, red, yellow 10%, #1E90FF 50%, white);

    Example: closest-side vs. farthest-side for a circle.
    The size of the circle on the left is determined by the distance between the start point (the center) and the closest side, while the one on the right is the distance between the start point and the farthest side.

    radial_circle_size

     background: -moz-radial-gradient(circle closest-side, red, yellow 10%, #1E90FF 50%, white);
     background: -moz-radial-gradient(circle farthest-side, red, yellow 10%, #1E90FF 50%, white);

    Example: contained circle.
    Here you can see the default circle on the left, and the version of the same gradient but contained on the right.

    radial_contain

     background: -moz-radial-gradient(red, yellow, #1E90FF);
     background: -moz-radial-gradient(contain, red, yellow, #1E90FF);

    Repeating Gradients

    If you would like to repeat a gradient, you should use -moz-repeating-linear-gradient and -moz-repeating-radial-gradient.

    In the examples below, four color stops are specified in each case, and are repeated indefinitely.

    repeating_gradients

     .repeating_radial_gradient_example {
        background: -moz-repeating-radial-gradient(black, black 5px, white 5px, white 10px);
    }
     .repeating_linear_gradient_example {
         background: -moz-repeating-linear-gradient(top left -45deg, red, red 5px, white 5px, white 10px);
    }

    Demo

    Check out our interactive demo of linear and radial gradients for more examples.

    Note that the gradient syntax has changed between Firefox 3.6 beta 1 and beta 2, so if you used gradients with beta 1, you may need to update your code.