1. Responsive viewport units

    With all this new fangled talk of responsive web design, its about time that we had a poster child CSS unit to go with it. So move over em, CSS3 Values and Units introduces a bunch of new viewport units that are getting ready for their time in the limelight.

    Motorola recently implemented support for these viewport length units and they’ve now found their way into Chrome Canary, so we can now start to experiment with them. They are also supported in IE9, although the vm unit has been updated to vmin since then.

    Introducing vh, vw, and vmin

    The vh unit stands for viewport height, vw for Volkswagen viewport width, and vmin represents whichever of vh or vw is the shortest length.

    The values used can be somewhat confusing if you’ve not used these units before, as 1vh represents 1% of the current viewport (the content area of the browser window) height, rather than 100% as you may expect. Therefore if you want an element to be the full height of your viewport you should set it to 100vh. As you would expect, vw works exactly the same way as vh units.

    If you have a widescreen monitor and your browser window is set to full screen, the width would be wider than the height. In this case the vmin unit would be the same as the vh unit.

    The viewport units are dynamic rather than static, so if you resize the browser window, the computed value of the units will also change. If for example your browser window is 1000px wide, and element with a width of 10vw would be 100px wide. If you shrink the browser window to only 100px wide, the width of the element would resize with it to 10px wide.

    A responsive example

    One of the big issues with using multi-column layout is that you need to endlessly scroll up and down the page to read each column if the height is taller than the viewport. The viewport units mitigate this somewhat, as you can set the hight of the element with multi-column applied to it to be smaller than the viewport height (but remember to take the margins into account). You still have the issue of horizontal scrolling if you restrict the height, but this may be an ok solution if you’re designing for something like a tablet device.

    I’ve created a quick example that uses this technique. Go and check out my multi-column responsive viewport example in Chrome Canary to see it in action. It should look something like the following screenshot:

    As the scrollbar is hidden by default in Mac OS X Lion, its a bit difficult in this example to see that the text is scrollable horizontally.

    Setting the width and height to respond to the viewport size is trivial with the vh and vw units:

    article > section {
        column-width: 22rem;
        column-gap: 2.6rem;
                    
        height: 80vh;
        width: 80vw;
            
        overflow: scroll;
    }
    
    

    This sets the height to be 80% of the viewport height, and the width to be 80% of the viewport width. The width of each column is set to be ideally 22rem (220px in this case) wide, but the browser can adjust this as needed. Finally overflow is set to scroll so that additional columns are hidden and can be scrolled into view, rather than overflowing to the right, and potentially overlapping any element that we place there.

    I also set some margins on the body element to give some breathing space. This also scale with the viewport size, to be 2% of the viewport height top and bottom, and 10% of the width left and right:

    body {
        margin: 2vh 10vw;
    }
    
    

    With this, you have a truly responsive design (at least with a simple example such as this), without even touching media queries. Imagine what untold powers they will bestow on you when you combine them? Add Flexbox to the mix, and we’ll really be cooking on gas.

    1 month ago  /  29 notes  / 

  2. What’s new in CSS3 Values and Units?

    In CSS3 the values and units we can use in CSS properties are defined in the appropriately named CSS Values and Units specification, with the exception those relating to colour and images, and the pre-defined keywords specific to individual properties.

    This spec gives us one new CSS wide keyword to play with (the initial keyword), five new relative units for lengths, five new functional notations, and various new types and units to support new CSS3 modules such as Grid and Flexbox layout, Transitions, and Transforms.

    CSS-wide initial keyword

    CSS2.1 added the first CSS-wide keyword to every property with the inherit keyword. CSS3 adds to this with the initial keyword. When you set a property’s value to initial it will set the value to what is defined as the initial value in the CSS specification for that property. Note that this is sometimes, but not always the same as the default value set in the user-agent style sheet. For example the initial value for various margin and padding properties is 0, but the default value given by the user-agent depends on the element to which it applies.

    The initial keyword can be useful if an element is inheriting unwanted styles and the original styling is desired. It is probably not something you will need to use often, but it is a useful tool to have on occasions. This is currently only supported by WebKit and Firefox (with moz prefix: -moz-intitial).

    Take a look at the initial keyword demo I prepared to see this in action. This currently requires a Gecko or WebKit browser at the time of writing.

    Font relative length units

    The rem unit

    The rem unit is perhaps my favourite new part of CSS3 Values. It stands for root em, and if you already understand how ems work (I assume that is most of you?) then you’ll be right at home. They are only subtly different, but it makes them easier to work with.

    The root part of the name refers to the root element, or the html element in HTML and the initial svg element in SVG. With regular ems the size of 1em is set to value of the font-size property of the current element, or the size of the parent element’s text size when used with the font-size property itself. The font size varies from element to element, so the size of an em is not consistent across the document. This requires a lot of calculation when you are tying to line elements up or are tying to compose text to a vertical rhythm.

    The rem value however stays consistent across the document, as 1rem is always the same size as the font-size of the html element (or root of which ever language you are using). If you want a margin to be a certain length, you just need to calculate it once for any element. If you want to make the maths as easy as possible you can set the html element to have a font-size of 10px (or another multiple of 10), then set the desired body copy size on the body element, such as font-size: 1.2rem for 12px. Now you get the scalability benefits of ems along with the ease of use and predictability of pxs.

    The only downside is the browser support. Its supported in IE9, Firefox 3.6+, Safari 5+ and Chrome. It is also coming to Opera 12, which should hopefully be released soon. As Opera users generally upgrade fast, and Firefox <3.6 is only around 1% market share, your only real issue in the near feature will be those users stuck on IE6–8. Using a fallback is easy if you set the root font size to 10px, as you can set every size you set in rems to the equivalent px size. For example 2rem is 20px, 1.7rem is 17px, and so on. It adds a lot more page weight however.

    I’ve prepared a rem unit demo which shows how you can follow a vertical rhythm using this unit.

    The ch unit

    The ch unit is equal to the width of the 0 (zero) glyph in the font used by the current element. This is mostly useful when using monospace fonts, where all glyphs are the same width. For example, if you have a pre element where you want it to wrap after a 55 of characters, you can use width: 55ch; unit.

    This unit is currently only supported by Internet Explorer 9 and Firefox.

    Viewport relative lengths

    There are three viewport relative lengths: vh, vw, and vm. These are relative to the size of the initial containing block, or in other words the viewport. If you resize the viewport, such as changing the size of the browser window, then the size of elements specified in these units will change.

    The vw unit

    This is relative to the width of the viewport. One vw unit is 100th of the width of the viewport. If the viewport is 1000 pixels wide then 10vw would map to 100px.

    The vh unit

    The vh unit works the same way as vw, but is relative to the height of the viewport instead.

    The vm unit

    The vm unit maps to whichever of the viewport width or hight is the smallest. There is some talk of dropping this as the same can be achieved using the min() functional notation.

    These new units can be very useful if you don’t want something to end up larger than the viewport. One use case I’ve had for these is while using multi-column layout. You often don’t want text using multi-column to be taller than the screen size as the user will have to scroll up and down for each column. With vh you could use for example height: 95vh which would make it 95% of the height of the viewport, no matter how tall the viewport is. You could also imagine them being useful for things like slide shows, video players, and mobile.

    You might think these units sound great, but unfortunately they currently only work in IE9 and above, so it will be some time before we can used them.

    The rest

    There are new units for angles (deg, grad, rad, and turn units) and times (s, ms units. These are used in CSS3 2D/3D Transforms, and CSS Transitions respectively. There are also new units for frequencies (Hz, kHz units). These are used in the CSS3 Speech module.

    There are new layout specific units: fractions using the fr unit, and grid units using the gr unit.

    It doesn’t make too much sense covering these, without coving the full spec for which they are used, so I will leave them for a later date. There are also five functional notations, which require in-depth explanation, so they deserve their own post. I will cover these in the near future. These are mathematical expressions (calc(), min() and max()), cycling values (cycle()), and attribute references (attr()).

    I hope you find some useful ways to use these new values and units that we now have to play with.

    7 months ago  /  87 notes  / 

  3. What’s new in Android 4.0 for Web Developers?

    Google recently announced the Ice Cream Sandwich version of Android, along with a new version of the WebKit-based browser. Lets have a look at what is in there that’s of interest for web developers.

    User agent switching, or a knock to the mobile specific site?

    When I was working with web site compatibility at Opera, one of the biggest complaints we got time and time again was when a popular site switched to giving the mobile version of the site rather than the desktop version. Despite perceived wisdom from developers that users are in the mobile context and want mobile optimised sites, the reality is users screamed blue murder. Especially when the site gave no option to switch back. The reasons were usually two fold. One: many users knew their way around the site and where they had to go (even when they only accessed the web on a mobile device) and two: often they wanted to use a feature that the developers had decided the mobile version didn’t need. Many of these users couldn’t just wait until they were on a desktop PC to use those features as their only way to access the web was through a mobile (think rural China, India or the Philippines for example).

    One perfect example was GMail. If you tried to sign up for an account (no one does that on mobile right?) it would say something like sign up for an account on a PC. These users were completely locked out of the site with no way to get an account.

    I suspect Google has been getting the same complaints Opera was getting, especially as Android is starting to become popular in developing countries. For the Android 4 browser, they have added a way to switch to the desktop site on a per tab basis:

    To get the most out of web content, users can now request full desktop versions of web sites, rather than their mobile versions. Users can set their preference for web sites separately for each browser tab.

    If I’d hazard a guess about how they do this, then it would be that they switch the user agent string to that of a desktop browser such as Chrome. That way the site developer will think it is a desktop browser and will give the desktop site. If they cloak well enough, there will be no way for the developer to force users into using the mobile site. I think this is a good thing, as it will open up choice to the user, and force developers to think about making their regular sites as friendly as possible. This is exactly what the mobile first brigade have been preaching. I suspect things like Media Queries will still work as expected in desktop mode. It will certainly put a dent in the firearms of those that want to browser sniff to give (or try to give. It always goes wrong. I’ve lost count of the amount of issues I had to deal with related to sever side browser sniffing for mobile browsers going wrong, across almost every major site) a tailored experience to mobile devices.

    So to recap, to guarantee a good experience on Android, you will need to make sure both your mobile site and your desktop site is mobile friendly. Or use one site and adapt via things like media queries.

    Roboto, a new high DPI optimised font

    Times change fast on mobile. Back when Android was first released, Google worked with Ascender Corp to produce the Droid family of fonts. One of the main design goals was to produce a font that worked well at small sizes on the restricted resolutions of mobile devices at the time. Thus, the letterforms were condensed to fit as maximise how much text could fit on screen.

    Fast forward to today and mobiles are ever increasing in both DPI and screen real estate (Galaxy Nexus has a 4.65 inch display at 330ppi!), and mobile platforms have expanded to tablets. With these new circumstances, Google has developed a new font in house by Christian Robertson called Roboto.

    The font has been created from scratch for high DPI screens. It is a geometric font, somewhat reminiscent of Helvetica. As it is the default font, this is the font your site will be using unless you specify otherwise. You should be able to use it where you use arial or helvetica today without any problems. As it is included in an open source product, it will assumably be available to download freely, just like Google allowed with the Droid family. Be careful if you were planning to use it on desktop platforms however. In a comment in defence of the font, Robertson stated:

    since Android doesn’t use much of the nastiness that is TrueType hinting, Roboto is not hinted to support older Windows browsers, for example.

    He mentions a few of the design choices in that post, and it is will worth a read. It remains to be seen whether the font gets accepted in the design community, and we will have to see it in its native environment, but I personally feel the UI looks much more fresher with it. I’m unsure of the Droid family, or any other fonts are also available for developers. I expect there should be at least one serif font, but you never know.

    WebKit enhancements

    One of the key things for web developers is the capabilities of the web browser. The Android browser has always lagged its desktop cousin, and was stating to get a bit of a bad reputation with web developers. Although they haven’t switched to Chrome (yet) in Android, we do get a new version of WebKit. The official docs report that this is WebKit 534.30. By comparing UA strings, it looks like this is the same version used by Chrome 12. However, just because the desktop version supports a feature, it doesn’t mean the code path was enabled on the Android branch of WebKit, or any porting work was done to expose a feature to the browsers.

    Performance improvements

    The Android team has upgraded to a newer version of V8 with crankshaft support. According to the Unofficial Google system blog in benchmarks run on a Nexus S device, the Android 4.0 browser showed an improvement of nearly 220% over the Android 2.3 browser in the V8 Benchmark Suite and more than 35% in the SunSpider 9.1 JavaScript Benchmark. That’s not too shabby.

    New on phones

    While tablets have been running Honeycomb, phones have been stuck on Gingerbread. If you’re developing towards phones, then all the features added to Honeycomb will be available to you for the first time. Highlights include:

    New since Honeycomb

    There are not a huge number of toys to play with, but there are a few including:

    Thanks to caniuse.com for the comparison data.

    What’s missing?

    So that WebKit version that corresponds to Chrome 12? How does it really stack up? Well a pretty huge difference actually. Some of the key things still still missing include:

    • WebGL
    • WebWorkers
    • WebSockets
    • Server Sent Events
    • IndexedDB
    • Drag and Drop
    • History API
    • HTML5 Forms (would be very useful on mobile)
    • Progress and Meter
    • File Writer
    • SVG Filters
    • Web Notifications (these are almost like they were designed for mobile)
    • WOFF (although does anyone use WOFF now TTF is well supported?)

    This is not to mention the features that have been added since Chrome 12. Our new Chrome overlords can’t come soon enough.

    So where are we at?

    We have some thinking to do regarding desktop sites on mobile being within easier reach, no matter if we like it or not. We have a new font similar to Helvetica as a new font, and a faster more standards web browser to play with. On the whole it is a competent update, but hardly earth shattering for web developers. The Safari browser on iOS is still ahead in a number of key areas in terms of standards support. With Opera Mobile 11.50 reaching 285 on the HTML5test (not featured on the site yet, nor is Android 4), I expect that still has the best standards support on Android currently.

    7 months ago  /  34 notes  / 

  4. Web Notifications

    One of the traditional advantages of native apps over the Web is that they can access the platform’s built in notification system. Mobile operating systems generally have their own baked in, while desktop OS like Mac OS X have commonly found 3rd party notification systems such as Growl.

    In the near future, we should be able to take advantage of this kind of functionality in our web apps as well. The Web Notifications specification provides us with this ability. This defines what are known as simple notifications. With simple notifications it is possible to create a notification which contains an icon, title, and body test. This can then be displayed by the notification system that the browser/user-agent hooks into. The spec doesn’t define this, so the user-agent can either roll its own, or use an existing system made available by the operating system.

    Current support

    The support situation doesn’t look too good at present. There are two implementations, one in Chrome, and one in Firefox Mobile. There is no support in desktop Firefox, and no support in the Android browser. The two implementations are far from interoperable, and both diverge quite a bit from the spec. The spec divergence is assumably because the spec has changed since it was implemented. It is possible to write code to make notifications work in both browsers however, although it won’t follow the current spec. With some more work it may be possible to write a polyfill though.

    Displaying a notification

    Checking and asking for permission from the user

    As notifications can be intrusive (imagine what advertising companies and spammers could do with it if they could just post notifications as they saw fit?) the first thing you need to do is request permission from the user. You can also check what the current permission level is, so that you can take appropriate action.

    In the spec this is handed off to the Feature Permissions spec. This spec defines a common model that will be used by all features that have to ask the user for permission. You can ask for the current permission level using something like:

    var level = navigator.permissionLevel("notifications");
    
    

    The permissionLevel method accepts a string that identifies the feature (“notifications” in this case), and returns one of the permission values USER_ALLOWED, DEFAULT_ALLOWED, DEFAULT_DENIED or USER_DENIED. The default value before asking for permission is either DEFAULT_ALLOWED or DEFAULT_DENIED. It is up to the user-agent to define what the default value is. You could imagine that in a web browser on the Web it would be DEFAULT_DENIED (this is how both current implementations act), but with installable applications such as Widgets, permissions could be set up front during installation and default could be set to DEFAULT_ALLOWED.

    If the permission level is DEFAULT_DENIED, you have to ask the user for permission. This is done with the requestPermission function. Like permissionLevel it accepts a feature string as an parameter. The requestPermission method is asynchronous so it also accepts a callback parameter that fires after the user has responded to the prompt to give or deny permission. This gives you a chance to respond to the users choice.

    It is important to note that you can not just call requestPermission in script. It is required that it can only be called after a user gesture, such as when they have pressed a key, or clicked a button or link. You can do this with an onclick event handler function for example. This is presumably to stop malicious scripts from inundating the user with requests without the user taking any action.

    This would all be well and good, but neither of the implementations currently work this way. In Firefox Mobile there is no way (that I could see) to request the permission level or to ask for permission. Instead, Firefox Mobile asks permission automatically when you try to create notification. Chrome on the other hand defines similar but different methods on the NotificationCenter interface–accessed via window.webkitNotifications–along with methods for creating the notifications (more on them later). If you understood the previous concepts then it is easy enough though. Lets look at a quick example using WebKit’s API:

    var level = webkitNotifications.checkPermission();
    
    document.getElementById("permission").addEventListener("click", function() {
        // if checkPermission returns 1 then permission needs to be requested
        if (level === 1) {
             webkitNotifications.requestPermission();
        }
    }, false);
    
    

    In the example above we first check the permission level. In a real example we would probably do something with this such as show, hide, or disable a button to request the users permission.

    Next we add an event listener to an element, and when the click event fires we check if the permission level is 1 (PERMISSION_NOT_ALLOWED), and then request permission if so. A dialog should then show in Chrome asking to accept or deny permission. If the user accepts the permission value will change to 0 (PERMISSION_ALLOWED) and if they deny it will change to 2 (PERMISSION_DENIED). If the user denies access then we can not ask for permission again unless the user goes into settings and removes the block.

    As you will be able to see, the basic concept is the same as the spec, but the access point and values are quite different.

    Creating the notification

    Once the user has given permission then we can create the notification. As is common with the support for this spec, there is three different ways: the spec, WebKit implementation, and Gecko implementation.

    The spec defines that notifications are created as follows:

    
    var notify = new Notification("avatar.png", "Notification title", "Notification body text");
    
    

    In WebKit and Gecko we use the createNotification method on the same interface we used for checking for permission. The Gecko interface is named slightly differently, uses the moz prefix and can be found on the navigator object instead. It also reorders the parameters just to make life more interesting:

        var notify,
            iconURL = "http://a2.twimg.com/profile_images/301953578/Picture_4_normal.png",
            title = "You have a new notification",
            desc = "Isn\u2019t that fantastic?";

        // creating a notification in Gecko 
    if (navigator.mozNotification) {
        notify = navigator.mozNotification.createNotification(title, desc, iconURL);
    } else if (window.webkitNotifications) {
        // create same notification in WebKit.
        notify = webkitNotifications.createNotification(iconURL, title, desc);  
    }
    

    Note that the URL for the icon is last in Gecko (it is also optional), and that WebKit use plural for webkitNotifications. If you don’t want to set one of the parameters you can always send an empty string. Once we’ve finished we end up with a notification object in all three versions.

    Showing the notification

    This is the easy part. All three use the show() method on the notification object!

    notify.show();

    After calling this we will see our notification on screen. Chrome rolls its own UI for notifications, which is shown at the top right of the screen by default. Firefox Mobile uses Growl on Mac and the native notifications draw on Android.

    Responding to events

    There are a number of things we can do once a notification is shown:

    Reacting to showing the notification

    When a notification is shown the show event is fired. Except in the WebKit implementation it is the display event. And the Gecko implementation doesn’t support this at all. We can handle the show/display event to respond in some way to the notification being shown:

    notify.onshow  = notify.ondisplay = function() { setTimeout(function() { notify.cancel(); }, 3000); }
    // after we call show(), the show event will fire and will be handled by the line above
    notify.show();

    In this example I’m using either an onshow or ondisplay event handler to set the timeout to 3 seconds from the moment the show (spec) or display (WebKit) events are fired. Once the timeout is over cancel() is called, which closes the notification (Gecko doesn’t support this either).

    Reacting to errors

    After calling show(), if there is an error that causes the notification not to show (the spec doesn’t define what these errors might be), the error event is fired. We can then handle the error gracefully. Except in Gecko, where errors are not supported. You’ll be glad to know that WebKit and the spec match in this case:

    notify.onerror  = function() { 
        // oh no error! fallback to our favourite alert
        alert(title + "\n" + desc);
    }
    //show the alert and see if there are any errors
    notify.show();
    

    Reacting to clicking on the notification

    If the user clicks (or touches, or otherwise interacts) with the notification, then the click event is fired. This is consistent across the spec, WebKit and Gecko, although it isn’t mentioned in the WebKit spec for some reason. It can be useful for things such as displaying the email mentioned in a new mail notification, or showing the event linked to a calendar event notification.

    notify.onclick  = function() { 
        // go to email
        showEmail(msgId);
    }
    //show the alert
    notify.show();

    Reacting to closing the notification

    When a notification is closed, such as by the user, by the system, or by calling cancel() the close event is fired. This is consistent across the spec, WebKit and Gecko:

    //This will be called when the notification is shown, and will close it in 2 seconds
    notify.onshow  = notify.ondisplay = function() { setTimeout(function() { notify.cancel(); }, 2000); }
    //Once the notification is closed, it will annoy the user with an alert!
    notify.onclose  = function() { 
        alert("You dismissed the notification, so I’m going to pop up!");
    }
    //show the notification 
    notify.show();

    Other options

    There are a couple more options not covered above.

    Notification direction

    It is possible to set the direction of the content in the notification for left to right and right to left text. This is set using the dir attribute of the Notification interface. The default is auto which sets the directionality to the directionality of the Document object. You can set it manually using notify.dir = "rtl" (such as for Arabic or Hebrew text) or notify.dir="ltr" for example. This method is not mentioned by the WebKit spec but it is supported. It is not supported by Gecko.

    Rich notifications using web content

    It is also possible to create notifications that use web content such as HTML or SVG. This was taken out of the Web Notifications spec however, and placed in its own Web URL Notifications spec. I will not cover it in this article as the spec has not been edited in a year and still follows the conventions in the WebKit implementation (such as using the NotificationCenter interface) rather than the newer style found in the Web Notifications spec. I expect this will be updated some time in the future to match the newer spec.

    Future implementations

    I’m not aware of any plans to update Gecko or WebKit to the newest spec. The differences are currently quite big, so I would guess they are waiting for the spec to stabilise. Web Notifications are currently on PhoneGap’s roadmap for December of this year. If this makes it then it will be possible to take advantage of the native notification support on the platforms that PhoneGap supports.

    Demo time

    I’ve created a quick, simple demo which works in both Chrome and Firefox Mobile. It attempts to take care of some of the implementation inconsistencies with the spec, but not all. I still use the NotificationCenter to create notification objects and check for and set permissions. It is left as a task to the reader to create a proper polyfill.

    In the demo you can click the authorise button to grant access if using WebKit. Gecko doesn’t need this so it will be disabled. Once the permissions are set you can click on the notify me button to show the notification. After three seconds it will automatically close. On a real site you should be careful of the accessibility considerations of showing and hiding notifications.

    View the Web Notifications demo (Requires Chrome or Firefox Mobile (including the emulator)

    View source to see exactly how it works. I’ve kept the styles and JavaScript in one file to make it easier to read.

    7 months ago  /  79 notes  / 

  5. Made in England from polished Ankole cattle horn, the only thing not to like about these whisky tumblers is that they’re sold out. They’re ethically sourced and made in a 170 year old horn works. I’ve always liked natural materials mixed with minimal clean lines, so these sound like the perfect accomplice to a fine single malt Japanese or Scottish whisky. If only they ever come back in stock.

Best Made are famous for their hand crafted axes, but they sell a whole host of amazing objects. Go check out the Best Made web site for more information.

    Made in England from polished Ankole cattle horn, the only thing not to like about these whisky tumblers is that they’re sold out. They’re ethically sourced and made in a 170 year old horn works. I’ve always liked natural materials mixed with minimal clean lines, so these sound like the perfect accomplice to a fine single malt Japanese or Scottish whisky. If only they ever come back in stock.

    Best Made are famous for their hand crafted axes, but they sell a whole host of amazing objects. Go check out the Best Made web site for more information.

    7 months ago  /  130 notes  /   /  Source: bestmadeco.com

  6. New standards support in Opera 12 alpha

    I couldn’t find anywhere that lists the new standards support in Opera 12 alpha all in one place, so I thought I’d write it up here for my own benefit. You might also find it useful.

    Opera 11.51 uses Presto 2.9, milestone 168, while while the alpha version of Opera 12 has been upgraded to milestone 220. The way Opera works is they have regular milestone releases of their core Presto rendering engine, that may include one or more tasks. These tasks could be anything from something big like a whole new feature (e.g. WebGL), to a raft of performance enhancements, to a group of bug fixes for site compatibility reasons.

    The latter doesn’t get much column inches but they’re a vital part of the health of a browser. There will be hundreds, if not thousands of these small fixes in the alpha release. In theory, with every new release the browser will work better with the top sites (well until someone releases a new site that wasn’t tested, and the process of identifying issues, analysing, making test cases, bug fixing, integration, and releasing happens all over again), and existing features will get more compliant with the spec.

    This blog post is about the new features though, so lets take a look at what they are.

    HTML5 parser

    This is probably the star of the show in Opera 12 alpha, even if perhaps the least glamourous. The old HTML4 parser has been thrown away and replaced with Ragnarök, the new HTML5 parser. If you code your pages correctly then you will not notice much difference, but if you do not create well formed markup (such as using incorrect nesting), then Opera will render more consistently with other browsers. This is because up until HTML5, the HTML spec only defined what should happen when markup was valid. Unfortunately this wasn’t enough as many sites do things incorrectly. Now in HTML5 the error handling is defined, so all browsers should in theory do the same thing. I know this was a huge task in of its own, but it will likely fix thousands of pages.

    You do get some new things to play with though. With the HTML5 parser, SVG and MathML can be used in HTML documents. Previously they had to be used with documents served as XML (such as XHTML).

    Enhanced HTML5 Video

    Opera’s HTML5 video support has been enhanced to add two new attributes and two new DOM properties:

    Preload attribute

    The preload attribute allows you to control if the video resource is automatically downloaded on page load. It accepts three values: none, metadata, and auto.

    If you use preload="none" then the resource will not be downloaded in advance of pressing the play button (or other method of starting the download). You could imagine this being useful on constraint networks or when multiple videos are included in one page.

    The metadata value will fetch the video metadata, such as the first frame (e.g. to use as a poster placeholder), duration of the video, size, track list, etc.

    The auto value says that the browser is free to download the entire video resource without the user explicitly requesting it, or a script fetching it. If you just use the preload attribute on its own without a value, it is equivalent of using auto.

    Not specifying a preload attribute at all is left for the browser to define, but the metadata value is suggested as a default value in the spec. Although the author can specify these values, they are not gospel. By spec, the user agent is allowed to just use the value as a hint and do what it thinks is best for the user. A mobile browser for example could preload on wifi when using the auto value, but just download the metadata if using the radio connection.

    Muted attribute

    The muted boolean attribute defines if the audio in a media file is muted or not. If the muted attribute is present the sound is disabled. This attribute is not dynamic, so if the attribute is added via script at a later date it will not mute the sound. It only effects the default state.

    Buffered property

    The buffered property (called attribute in the spec, but named property here to avoid confusion with attributes in HTML) is a member of the HTMLMediaElement DOM interface. If you call media.buffered it will return a TimeRanges object. This represents the range of the resource that has been buffered by the browser. This object contains the length of the buffered resource, the time where the buffering starts and the time when it ends.

    Seekable property

    The seekable property works much in the same way as the buffered property, returning a TimeRanges object. However, this represents the range that the browser can seek to in the resource. If the browser can seek to anywhere in the file then the range will be the entire video length.

    Complete ES5.1 support

    Opera has lagged behind for quite a while with its ECMAScipt 5 support. With Opera 12 alpha it now has complete support and passes all the tests in the test suite, bar one test which is believed to be invalid.

    This improved support includes:

    • Object.create
    • Object.defineProperty
    • Object.defineProperties
    • Object.getPrototypeOf
    • Object.keys
    • Object.seal
    • Object.freeze
    • Object.preventExtensions
    • Object.isSealed
    • Object.isFrozen
    • Object.isExtensible
    • Object.getOwnPropertyDescriptor
    • Object.getOwnPropertyNames
    • Function.prototype.bind
    • Reserved words as property names
    • Strict Mode

    Now we are more or less just waiting for older browsers to die out before ES5 is usable across the board.

    DOM 3 Events isTrusted property

    The isTrusted property from the Event interface has been added. It is a boolean property that reports if the event was generated by the user agent (a trusted event, thus true) or by a script (untrusted event, thus false). Trusted events are given heightened privileges. See trusted events in the DOM3 Events spec for further details.

    Microdata

    Opera 12 is the first browser to support the HTML Microdata spec (formally specified in HTML the living standard (née HMTL5)). This is a way to add machine readable semantic structured data to a document. If you know about Microformats then it is roughly the same idea, except it uses its own set of attributes and API rather than using (or abusing, depending on which camp you are in) existing HTML attributes. This spec is fairly controversial as it also steps on the toes of the pre-existing RDFa specification.

    In the end it will be the survival of the fittest with which one wins out. Most likely driven by user agent and developer adoption. Microdata looks like it is winning out so far with the former (with Motorola also showing interest in implementing it in WebKit), and the Schema.org initiative (a collaboration between Google, Microsoft and Yahoo!) have also chosen it. The scheme.org work is also not without controversy itself, so it is still all to play for.

    Typed Arrays

    Support has been added for ECMAScript Typed Arrays. This is a specification made by the Khronos group to support WebGL. Typed Arrays allow the developer to work with binary data. This is needed for high performance tasks such as 3D games. The spec itself states:

    ECMAScript [ECMA-262] has traditionally been used in contexts where there is no access to binary data. Where binary data has needed to be manipulated, it is often stored as a String and accessed using charCodeAt(), or stored as an Array with conversion to and from base64 for transmission. Both of these methods are slow and error-prone. For example, reading binary data as 32-bit integers requires manual conversion of 4 source bytes to and from the target type. Reading floating-point data is even more expensive.

    As web applications gain access to new functionality, working with binary data has become a much-demanded feature. Current specifications such as the File API [FILEAPI] and Web Sockets [WEBSOCKETS] would benefit from being able to read and write binary data directly in its native form. Specifications such as WebGL [WEBGL] require this functionality to meet acceptable performance characteristics.

    WebGL and hardware acceleration

    Opera’s graphics library Vega is now hardware accelerated in Opera 12 alpha. All of the browser UI and web page content is rendered by the GPU if possible.

    Having hardware acceleration and Typed Arrays opens the door for WebGL. WebGL is the 3D context for the canvas element. It is a low level 3D graphics API, which is based on OpenGL ES 2.0, supporting GLSL shaders. This allows for 3D applications such as games to be developed only using web technologies. Try out the HTML5 port of Emberwind to see what it is capable of. The game can be played using 2D canvas or WebGL so you can compare the performance difference between the two.

    Radial Gradients

    Linear gradients from CSS3 Image values were already supported by Opera. Radial gradients didn’t make the cut, but are now supported in Opera 12 alpha. As the name suggests, radial-gradient() allow for gradients made out of concentric circles or ellipses. There is also support for repeating-radial-gradient(). They both take the -o- prefix.

    Support for gradients has been extended so that as well as background/background-image, they can be used with border-image and list-style-image.

    For a preview of gradients in action check out Lea Verou’s pattern gallery in Opera 12 alpha.

    The rem unit

    Nothing related to Remy Sharp, although I’m sure it is his favourite part of CSS3, the rem unit from CSS3 Values and Units maps to the font-size of the root element (html in HTML). If the font size of the html element is 12px then 1rem will also be 12 pixels. This is useful when trying to achieve vertical rhythm on a page, as it is easier than calculating em sizes, which change element to element based on its parent.

    Bug fixes which are useful to know

    Although there were a lot of bug fixes, a few may effect developers and are useful to know:

    • The inset keyword on box-shadow now works on input elements
    • Co-ordinate handling has been improved, so values can be used larger than the magic 32768px without pages breaking in Opera. This has been a painful bug for quite a while!
    • HTML5 URL input fields (type="url") are now the same width as regular text fields
    • display: list-item has been updated to be compliant with the CSS 2.1 spec
    • border-radius will now clip replaced content. No more images overlapping over your nice rounded corners! Not that round corners are in fashion any more
    • HTMLHeadElement.profile has been removed due to being obsolete in the HTML5 spec
    • addEventListener and removeEventListener’s capture parameter now defaults to false
    • XML documents no longer show a parse error when badly formed. They now just show an error in the console

    That is quite a lot of new features in a relatively short period of time, so I haven’t had chance to try them all myself yet. Opera 12 is shaping up to be a good release, and has even leapfrogged Chrome on the HTML5test with 346 points if you enable WebSockets, and is only 7 points behind if you keep them disabled. There is now a clear race on for first place. Chrome is not standing still and moving fast, but Opera 12 likely still has some things up its sleeve. HTML5 drag ‘n’ drop has yet to make an appearance for example, and getUserMedia() (access to the video camera) has been demoed on Android, so could make an appearance on desktop too. I wouldn’t bet against it when you see images such as the following in Opera’s press event:

    This alone would give Opera 20 more points on that particular browser test. Its certainly an interesting time in the browser wars, with a lot of toys for us developers to play with.

    7 months ago  /  49 notes  / 

  7. HTML5 scoped attribute

    The HTML5 spec adds the scoped attribute to style elements. What does this do, and how can it be useful?

    The scoped attribute is used to limit the scope of the CSS rules inside the style element to that element’s parent and all the children of the parent. All other elements outside of the scope do not get styled, even if the selectors match. It is a boolean attribute, so you can use scoped for HTML and scoped="scoped" for XML/XHMTL. The use of scoped style sheets is best illustrated with an example:

    
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <title>Scoped example</title>
            <style>
                p { color: black; }
            </style>
        </head>
        <body>
            <p>The text in this paragraph will be black</p>
            <div>
                <style scoped>
                    p { color: green; }
                </style>
                <p>The text in this paragraph will be green</p>
                <p>And in this paragraph too</p>
            </div>
            <p>This paragraph is out of scope so will be black</p>
        </body>
    </html>
    
    

    In compliant browsers, the two paragraphs inside the div element will receive a text colour of green, while all other paragraphs will be black. Any styles in the scoped style element only apply to the parent element (the div) and its children (the two p elements).

    There is a bit more to it though. Any @page rules in scoped style sheets are dropped. Also if a font is linked via @font-face then that font will not be used for elements out of scope, even if they have a font-family applied to them which matches the name given in the @font-face rule in the scoped style sheet.

    Why use scoped style sheets?

    The first thought might be why should I use this? When you put a style element within your HTML then it isn’t too different to using inline styles (minus the specificity concerns). I strongly believe that we should strive for separation of concerns, and John Allsopp makes some good augments about this on his blog.

    However, there are some valid use cases for it. One use case that comes to mind is when using demos in your page. Instead of giving everything ids or classes, you can use a scoped style sheet that you can guarantee will only apply to the demo. That is a bit esoteric compared to the average needs of web developers, but it hints at why it is really useful. Web components.

    The Web was primarily used for documents and our languages reflected this. We are increasingly seeing the Web also be used for applications as well. Web apps have their own requirements. We often need rich components and controls, such as custom sliders, buttons, carrousels, accordions, etc. A lot of frameworks have sprung up to fill this need, and the component model along with the shadow DOM will hopefully be the standardised solution to this.

    Components built with web technology usually have their own defined style and behaviour. We want the styling of these controls to be self contained and not leak out to the rest of the document. Scoped style sheets are one solution to this. It avoids having to hack in name spaces, such as trying to use a unique id and using this with each style rule (which can also lead to specificity hell), or inline style (which is even worse). With scoped style sheets we can be sure that the styles will only apply to the HTML of the component, and can style be easily overridden by other rules if we need to customise the component.

    Where can I use them?

    If you think Great! which browsers can I use this in? you’ll be frustrated right now, as no browser or user agent supports the scope attribute right now. There is work in progress in WebKit however, so it may land soon.

    Edit: This is now supported in nightly builds of WebKit.

    Wouldn’t it be nice…

    The main criticism I’ve seen about scoped style sheets is the mixing of concerns issues, and I more or less agree. What I think could be a solution to this (but someone smarter than me probably knows why it can’t be done) is to allow link and maybe style elements in the head to have an option for attribute, just as labels do. Then you could do something like <link rel="stylesheet" href="style.css" scoped for="scoped-element" /> which is scoped to the element (and its children) with the id specified. This would allow you to keep the scoped style sheet in the head of the document where it belongs.

    7 months ago  /  13 notes  / 

  8. What are CSS Shaders?

    Adobe announced a proposal for CSS Shaders at Adobe Max two days ago. This was backed by both Opera and Apple, and the spec will be developed by the FX Task Force at the W3C. For those of you who are not aware, the FX task force is an elite band of ninjas’s chosen from the ranks of the CSS and SVG Working Groups to work on specs common to both technologies. Their most notable work so far is perhaps the Filters Effects 1.0 spec, but they’re also working on a common model for Transforms and Animations.

    So what exactly is the CSS Shaders proposal, and how does it relate to the existing proposals and technologies? First I will introduce you to the required terminology (you can skip that section if you are already into computer graphics), then I will dig into the proposal and see what it can do. I’m basing this off the spec as I don’t have a build to play with.

    Shaders terminology

    A shader is a set of software instructions used to calculate rendering effects (usually) on a GPU. A graphics pipeline takes a representation of what will be rendering using 3D primitives (such as vectors) as an input, and through various stages in the pipeline transforms it, then renders it as a 2D rasterisation (pixels) onto a 2D plane (usually a screen). Traditionally, fixed-function pipelines were used, which support common pre-defined geometry and pixel shading functions (more on these below). With shaders, instead of using pre-defined functions, developers can program their own custom functions to do whatever transformations they want to specify. Due to the pipeline approach, shaders can be chained so that the output of one feeds into the input of the next one. This will be familiar to you if you’ve used SVG Filters or programs like Automator on Mac or Yahoo! Pipes.

    Their are two main types of shaders in the CSS Shaders spec, which I will describe below.

    Vertex shaders

    A vertex shader describe the properties of a vertex (the points at the corners of geometric shapes, usually triangles). These include the position and colour of the vertex, and the texture mapping. If you can imagine a model is represented as a number of triangles, with the vertices at each corner, the shader will transform these vertices, such as change the position in 3D space, the colour, or the depth. This could for example transform a flat shape, such as a flat piece of paper, into something that looks like it has a 3D perspective, such as the curved page of a book. The spec includes examples such as a page curl, waving flag or wobble effect.

    Fragment shaders

    Fragment shaders (terminology used in OpenGL and also CSS Shaders) can also go by the name of pixel shaders (used in Direct3D). Fragment shaders describe the properties of pixel, such as the colour, opacity, and bit-depth. As you can imagine from vertex shaders, a fragment shader manipulates these pixels, such as changing the colour. They can be used for things such as lighting effects or colour manipulation such as changing an image to greyscale or sepia tone. You’ve probably seen a number of these in graphics packages such as Photoshop. CSS Filters includes a number of pre-defined ones, but fragment shaders will allow you to define your own.

    The CSS Shader proposal

    Now you have a rough idea of what shaders are, what exactly is the CSS proposal for shaders? At its basic level, the proposal is to bring these effects to HTML and SVG content via CSS. Fragment shaders extends the capability of Filters so that you can define your own pixel manipulations, and vertex shaders brings the new capability of distorting the 2D HTML and SVG elements. The vertices will be drawn as a grid of triangles over the 2D plane of the element(s) in question, and they can be manipulated as mentioned above to make a faux-3D effect on the screen. Shaders are defined to work well with CSS modules such as Transitions and Animations, so that you can animate the distortions, such as turning elements into a waving flag, or a page that curls. As you can imagine combining multiple shaders and animations can produce some very sophisticated effects.

    Applying shaders with CSS

    A shader is applied via CSS using the filter property from Filters 1.0, or it can be applied to SVG using the filter element. The filter property/element is usually used for pre-defined filters. To use a custom shader you use the custom() function (or feCustom as a child element of the filter when using SVG elements) as the value. They can be chained with other shaders and built-in filters. For fragment shaders the custom function needs a url that points to the shader and arbitrary optional parameters. The shader is written using a shaders language, which defines the parameters it expects, if any. Vertex shaders are similar but also can accept a vertex mesh as the second argument. This defines how many vertices are used and if it maps to the border box, padding-box, content-box or filter box. The filter property accepts the functions as a space separated list to allow for chaining. Custom filters are also defined as a space separated list inside the custom() function. Lets look at a quick example from the spec to make this clearer.

    
     .old-book-page {
            filter: grayscale(1.0) custom(url('book.vs') url('old-page-paper.fs'));
     }
    
    

    The filter property in this example first uses the grayscale() built-in filter to turn the element black and white. It then feeds the output into the custom() function. This uses a vertex shader called book.vs which manipulates the flat element into an open book shape, then applies the old-page-paper.fs fragment shader to manipulate the pixels to give it an aged look. The shaders found at those URLs will define how these manipulations happen. They don’t define any custom parameters or a vertex mesh.

    If the elements the filters applies to looks like the following:

    After the filter is applied it will turn into the following:

    Lets look an example where the vertex mesh is defined and custom parameters are used. Transitions are also used to animate the vertex shaders.

    
    .waving      {
            filter: custom(url('wave.vs'), 20 20, phase 0, amplitude 50);
            transition-property: filter;
            transition-duration: 0.2s;
    }
    
    .waving:hover {
            filter: custom(url('wave.vs'), 20 20, phase 90, amplitude 20);
    }
    
    

    You may recognise the url function from the previous example. This links to the custom wave vertex shader. The 20 20 after defines the vertex mesh of 22 x 22 vertices. It may seem strange why it makes a 22 x 22 grid rather than 20 x 20, but I will describe later. The phase and amplitude parameters are defined by the shader. These two properties are transitioned over 0.2 seconds, which makes it wave like a flag. The example will look something like the following (minus any animations):

    Defining a vertex mesh

    In the above example we used a vertex mesh, which defines the vertices that can be manipulated by the vertex shader. This accepts three values: two integers and a box value. It is specified as the second argument (separated by a comma) in the custom function when using CSS, or using the vertexMesh attribute of the feCustom element when using the SVG syntax.

    The first integer defines the number of additional vertex lines (you can think of this as number of points on the y axis) and the second is the number of additional vertex columns (you can think of this as the number of points on the x axis). There is however two extra vertices than the number defined. This is because the default value is 0 0 which is one line and one column. In this case there are four vertices; one at each corner (top left, bottom left, top right, bottom right). You can see this in the diagram below:

    If you add 1 line and 1 column you get these four vertices at the corners plus the 1 you add in the centre of the row and column. Therefor the algorithm to calculate the number of vertices in each direction is n+2, and to calculate the number of lines or columns it is n+1. This may be confusing, so there is a note in the spec considering if the default should be 1 1 instead of 0 0. In the following diagram the vertex mesh is set to 5 4:

    The last parameter is the box value. This is used to align the vertex mesh to the box specified. If it is absent it defaults to filter-box. This is the border box plus additional filter margins (so that any additional content that through vertex or pixel manipulation is displayed outside the margin box is still visible). The other possible values are border-box, padding-box and content-box, which you are probably already familiar with from the CSS box model. If you are using SVG then border-box and padding-box is the equivalent of content-box. You could imagine a shader specifying a mesh similar to the one in the diagram above, using an explicit box value could be something like the following:

    
    filter: custom(url('whatever.vs'), 5 4 filter-box);
    
    
    Defining the shader

    This is the meat of the shader. It is trivial to add; you just use the url() function as the first argument of the custom() function in CSS, or in the vertexShader or fragmentShader attribute of the feCustom element for the SVG syntax. With this you point to the file where the shader is defined. Vertex shaders use the .vs extension and fragment shaders use the .fs extension. Writing the shader is where the hard part comes in. I expect most developers won’t write their own, and libraries will pop up that define the common ones that are needed.

    The proposal recommends that shaders should is written using GLSL ES. This is the OpenGL ES Shading Language (PDF link). This was chosen as it is already used in WebGL. Having consistency between both makes sense to me. It is a full programming language in its own right, and quite close to the metal, so it is beyond the scope of this humble blog post to describe how to use it.

    Passing parameters to the shader

    While shaders can be interesting in their own right, they are much more flexible when you can pass in parameters to affect the transformations that take place. You specify these in the custom() function, or the params attribute of the feCustom element if using the SVG version. This takes in space separated key value pair. The first is the name of the parameter (this will be defined in the shader) and the second is the value you are passing to it. This can either be true, false, a number (as used in the example above), an array (array( ‘[wsp]*’)), a transform (either a CSS 3D transform or a matrix), or a texture (texture()). With texture you can pass it the result of a previous filter or shader using the result() function. You pass it the name specified in the result attribute of the filter in question.

    Here is an example defining the filter, then a shader with a vertex mesh and a number of parameters:

    
    filter: grayscale(0.5) custom(url('groovy.vs'), 5 4, awesome false, randomness 15, stuff array(1 23 43 32));
    
    

    This will apply a grayscale filter. The texture which is outputted from this passed to the groovy vertex shader. This will create a vertex map of 6 lines (7 vertices) and 5 columns (6 vertices) attached to the filter box. It will then pass in the three parameters, do whatever the vertex filter defines to manipulate the texture then will output the result and rasterise it.

    Defining the filter margins

    There are filter margins outside the border box to give space for the various transformations. These can be set with 5 new CSS properties: filter-margin-top, filter-margin-bottom, filter-margin-left, and filter-margin-right work the same way as the the equivalent margin properties. The filter-margin property is the shorthand that works the same way as the margin property. If you are using the SVG syntax you can use the x, y, width and attributes on the filter element instead. If both are defined then the SVG attributes takes precedence.

    Relation to other specifications

    The CSS shaders spec relates most closely to the Filters 1.0 and WebGL specs. As explained earlier, the shaders spec uses the custom function from Filters 1.0. Fragment shaders are similar to filters, but allow you to define your own from scratch, rather than just being able to use the predefined filters in Filters 1.0.

    WebGL is a web-based version of the OpenGL ES 2.0 specification. It is a powerful low level 3D graphics language, which provides a 3D context to the canvas element. It provides both fragment and vertex shaders using the same GLSL ES Shader language, plus all the other 3D features. The use cases are quite different as WebGL works on content in the canvas element while CSS Shaders works on any HTML or SVG content. WebGL is a 3D drawing API similar to 2D canvas, while HTML and SVG is retained mode, using the DOM.

    The same trade offs, advantages and use cases with SVG Vs Canvas are likely with CSS shaders + HTML/SVG Vs WebGL. You’re likely to use WebGL if you want highly interactive 3D games where you don’t care about keeping access to what was rendered on screen and you’re making 3D models, while you’re more likely to use HTML/SVG + CSS shaders if you want to retain the DOM, such as keeping textual content as actual text, and just want to add some visual effects.

    The shaders spec is also defined to work with CSS transitions and Animations. The filter property is specified to be animatable. For interpolation to happen the filter values have to have the same number of filter functions and appear in the same order .

    8 months ago  /  161 notes  / 

  9. What’s slated for CSS4 Selectors?

    The CSS Working Group recently published the first working draft of CSS4 Selectors. “Wait…CSS 4? I thought CSS3 was still incomplete” you might ask. The spec process changed after CSS2.1. Instead of one monolithic spec, CSS3 was broken down into smaller bite sized chunks. Each chunk or module graduate to the Recommendation stage independently when they’re ready. As each module doesn’t depend on each other (typically. Some related modules might have dependancies, such as CSS3 Selectors on CSS Namespaces) work can start on the next level of the module–if there is demand for a new version–after the current level reaches REC. Therefor work on CSS4 specs will go on in parallel with CSS3 modules. The selectors specification is one such module where there is demand for some new features .

    Introducing Selectors level 4

    The CSS4 Selectors spec has already seen a large number of revisions since level 3. As it is still the first draft of the spec, it will likely change in numerous ways before it becomes a recommendation itself and there are browser implementations. Lets have a quick dig into the draft and see what has changed.

    Moving homes. In-N-Out the spec

    There are some selectors that were moved into CSS4 Selectors from other specs, and some that were removed and are looking for a new home:

    Pseudo-elements

    One of the first things you may notice about the spec is that pseudo-elements are gone from the spec. Don’t worry though, they will find a new home in a different spec in the future. I’m not sure if this will be its own spec or merged into another one. I wonder if this is to prepare for styling the Shadow DOM.

    UI state pseudo-classes

    While pseudo-elements were moved out, the user interface state pseudo-classes from CSS3 Basic User Interface have been moved into the spec. These target various states that UI components can be in, such as if checkbox is checked or unchecked or if a value is required or not. They were mapped to XForms states in CSS3 UI, but they are in general language agnostic. They’re perfect for styling HTML5 Form elements. I assume they were moved to put all the selectors in one place except pseudo-elements. Makes sense to me.

    Contextual reference element pseudo-class

    What a mouthful. This is the :scope pseudo-class. You might not have heard of this, but it comes from Selectors API Level 2.

    If you don’t understand what the :scope pseudo-class does then don’t worry. It is quite difficult to understand from the spec, and I had to ask the Lachlan Hunt myself. As far as I understand it, the :scope pseudo-class acts as a placeholder in the selector list. It is replaced by a specified reference element. In the case of Selectors API 2, the element can be specified as an argument in the querySelector, querySelectorAll and matchesSelector methods. This is much easier to understand if I show it in an example:

        var el = document.querySelector("#foo"); // returns first element with ID of foo
        var bar = document.querySelector(":scope > p", el); // returns equivalent of "#foo > p"
    

    In the above example, “:scope > p” and “#foo > p” are not 100% equivalent. The later will return the first p element that is a child of an element with ID of “foo”. With the former, instead of any #foo, it will only use the first #foo in the document. As multiple IDs are illegal the difference in this particular example will not show off too often, but as you can imagine, the difference is important when using a reference element can appear multiple times in the document.

    The :scope selector is most useful when reference elements are generated programatically, so it is not possible to write a static selector string. The selector is not currently implemented in any browser.

    Changes to existing selectors

    In CSS3 selectors, the negation selector (:not) can only accept a simple selector. A simple selector is either a type selector (an element name such as p or em), universal selector (the selector), attribute selector (those that target attributes such as [att], [att=val], etc.), class selector, ID selector, or a pseudo-class selector. Pseudo-elements and combinators (e.g. ul li, ul >li etc.) are not supported, and the negation selector can not be nested. These restrictions have been relaxed somewhat in CSS4 Selectors to also allow a selector list. Both simple and compound selectors are allowed. Pseudo-elements and nested selectors are still not supported however.

    New proposals

    There are quite a few new selectors that have been proposed in the new spec, including one that has been much demanded by web developers.

    Matches-Any Pseudo-class

    The :matches() pseudo-class is the standardised version of Mozilla’s :-moz-any() pseudo class. This is useful for when you need a number of similar selector strings, but change one part such as the pseudo-classes. Instead of writing li a:link, li a:hover, li a:visited, li a:focus, you can write li a:matches(:link, :hover, :visited). Only simple or compound selectors are allowed. Complex selectors, nesting and using within :not()is forbidden.

    Directionality pseudo-class

    The dir() pseudo-class selects elements depending on its directionality. This is commonly the direction of any potential text in the element, set with the HTML dir attribute. Note that the dir attribute does not need to be set directly on the element. It could be inherited from its parent. It does not match based on the CSS direction property.

    The currently defined values are rtl (right to left, e.g. used with Hebrew or Arabic text) and ltr (left to right, e.g. used with latin text). Other values are not invalid, but are not defined to do anything. This allows the spec to be extended if new values are needed (top to bottom for example?).

    Hyperlink pseudo-class

    The any-link() pseudo-class matches links, no matter if their history state is unvisited (:link) or visited. This is needed because once a link is visited the regular :link pseudo-claass does not apply any longer. This saves you having to specify both when you want to style both states the same way. The name is not set in stone, so if you have a better suggestion then get in touch with the working group.

    Local link pseudo-class

    The :local-link pseudo-class selects elements whose links are local links. If you use the plain :local-link pseudo-class, without parenthesis, then it matches elements that link to the current page. That is exactly the same URL as the document, sans any fragment identifier. Parenthesis can be added, taking a digit as a value. Using 0 (a:local-link(0)) will match a link that is the same domain. A value of 1 matches the domain and the first path segment. A value of 2 matches the domain and the first two path segments, and so on. For example, if the URL of the document is http://www.example.com/foo/bar/baz, the a:local-link(1) would match a elements with links that matches http://www.example.com/foo, while a:local-link(2) would match a elements with links that matches http://www.example.com/foo/bar.

    Time-dimensional pseudo-classes

    There are three time-dimensional pseudo-classes: :past, :current, and :future. These relate to time related rendering (or time-dimensional canvas as the spec says), such as speech rendering of HTML documents (text to speech). The :current pseudo-class matches the element that is currently being rendered (such as styling the image that is currently being spoken). The :past pseudo-class styles matches elements that were rendered in the past (e.g have already been spoken), and :future matches elements that will be rendered in the future (will be spoken). There is also a version of :current that takes arguments in parenthesis. This works in much the same way as the :matches() pseudo-class, where it matches any of the comma separated selector compound selector strings. I am not 100% if I got this one right, as I am not familiar enough with time-dimensional canvas.

    New tree-structural pseudo-classes

    There are two new tree-structual pseudo-classes: nth-match and nth-last-match. These work much the same way as nth-child and nth-last-child, using the same an+b notation. However you also include the of keyword and a selector string that is used to match a subset of the results. This is difficult to understand when reading the spec, but an example makes it clearer. If you have the selector button:nth-match(even of .active), instead of selecting all even button elements as with button:nth-child(even), it will first match the subset of elements with a class of active, then match the even elements from that subset.

    Grid-structure pseudo-classes

    There are three grid-structure pseudo-classes: :column(), :nth-column(), and :nth-last-column. In HTML individual cells of tables are marked up in rows (using the tr element). The column the cell belongs to is implied rather than than the cell being a child of the col element. Due to this one dimensional hierarchy, to style individual table cells based on the column it belongs to, we need the :column() selector. It accepts a list of one or more selectors. Based on the semantics of the language, it calculates if the cells belong in the columns that match the selector list. For example :column(col.total) selects all the td cells in the total column.

    The nth-column() and nth-last-column accept an+b notation as their argument, in the same way as other similar pseudo-classes. For example, :nth-column(odd) would select all table cells in odd columns.

    Reference combinators

    Reference combinators allow you to select elements that are referenced by ID by another element. One of the most common occurrences of this is when a label references the ID of its related control in the for attribute. You define a reference combinator by surrounding the attribute with forward slashes (/). For example, if you wanted to style an input element when you hover over its label, you could use the selector label:hover /for/ input (providing the label has a for attribute with the correct ID).

    The mythical unicorn: parent selector

    That most demanded of selectors is now in the spec. Well not quite. It isn’t just a parent selector. You can now select which element is the subject of the selector. Traditionally this is the right most compound selector in the selector string. This is currently defined with the dollar sign ($), but there is currently some debate on the mailing list, and will likely change. The compound selector that is marked as the subject is the one that will be styled by the CSS rule. If you have a selector such as ul li.selected, it will match an element that is of type li that is a decedent of a ul element. However, if you want to only style a ul if one of its li elements has a class of selected, you need to make the ul the subject of the selector like so: $ul li.selected. Now all your prayed are answered!

    This is the current state of play with the first CSS4 Selectors draft. Anything can and will change as the spec progresses. There are very little in the way of implementations of these features, so I can’t check if I understood them all 100% correctly. If I didn’t then let me know and I’ll update the post.

    8 months ago  /  36 notes  / 

  10. The makeup of the Open Web stack

    The Open Web has never had as many capabilities as it has today. We’re seeing an explosion in new or updated specifications, and prototype and stable implementations to go with them. This blog post will look back as the platform we have had available (Called Open Web 0 here) and then looks forward at what we are beginning to get now and into the short and medium term future (which I’ve labelled Open Web 1).

    Open Web 0: The AJAX age

    I’m informally calling this the Open Web 0, also known as Web 2.0 and AJAX. This is when the Web started to bloom as an application platform. JavaScript and DOM Scripting was suddenly taken seriously, and XHR liberated us. We could now pull in data from the server without those pesky full page reloads. Applications on the Web, through a web browser, blossomed. I call this Open Web 0 as all modern browsers today support the technology stack (although not always 100%) of this era. Of course, during the golden age of AJAX the support was lopsided, and IE needed special code paths, but this is by and large not needed for modern day IE.

    The Open Web 0 stack

    The stack of this era largely centred around HTML4 and XHTML. CSS2.1 was still being worked on, but was largely usable cross browser (except IE vintage of that era). On the scripting side ES3 was top dog, aided and abetted by XHR and DOM 2 (again with shims for IE). These were the days when we were living in the shadows of the first browser wars. IE had been laying dormant, fattened and inactive after all the market share it had drank up. Jerked awake from their slumber by the XHR powered AJAX revolution–a technology they created no less–the IE team was reformed and they started to play catch up and implemented the parts of the stack that they lacked.

    The Open Web 0 stack roughly consists of:

    Markup
    • HTML 4.01
    • XHTML 1.0 and 1.1 (the same except spec modularisation and the largely unimplemented Ruby Module)

    Semantics could be added to HTML or XHTML using existing attributes with Microformats.

    Styling
    Behaviour: ECMAScript, the DOM and APIs
    Graphics and Images
    • SVG 1.1 (largely unused due to lack of IE support at the time)
    • PNG, JPEG, GIF, etc.
    Video and Audio
    • No native support. Plug-ins such as Flash provided this capability
    Fonts
    • Only installed system fonts
    Other

    Open Web 1: the HTML5 application age

    We’re now moving into a new age. That of HTML5. The Web is truly becoming an application platform. Apps on the Web are becoming richer thanks to new APIs, there are efforts to make installable apps through the Widgets initiative, and platforms such as webOS, Windows 8 and the BlackBerry Playbook’s QNX based OS either use Open Web technologies as the way to write apps or one of a number of options.

    Flash was used to prop up the deficiencies of the Open Web in the past. It became the solution for video, and as a shim for supporting new fonts and cut and paste. It had capabilities the web didn’t have such as microphone and web cam access. We’re not quite there yet, as we’ve not fully arrived in the application age. We’re in the middle of that particular path, but Flash is well on the way to being supplanted by the Open Web. Flash will put up a good fight, and HTML owes a debt of gratitude to it for the inspiration, help and challenge it has provided, but the Web will win. All the momentum is currently on its side. Even Microsoft is playing along. Who would have thought that 6 years ago?

    The Open Web 1 stack

    The star of this particular show is HTML5. It swept XHTML and XML to one side and became the media darling. Like many things that crave the limelight, it has stolen credit for things it doesn’t do (No CSS and Geolocation are not part of HTML5). But it plays its role of front man and poster boy well. Even the men in suits talk about it, even if they have no idea what it actually is. Much of the real power of HTML5 comes from its associated APIs. These give it the ability to do things that real applications do, such as access client side storage, multi processes, graphics APIs, web cam and GPS access and so on.

    It is not clear what technologies should be included in the stack as many are still under active development. I’m including specs that are either stable and have implementations, or where there is no previous spec in its area but there is significant vendor interest in implementing in the near future. Some will fall by the way side or be replaced by competing specs. Some will be be replaced with newer versions of the same spec. Some of these might not arrive until the next generation.

    Markup and Semantics
    • HTML5
    • ARIA 1 (Accessibility)
    • MicroData (Semantics. See also RDFa for a rival that fills the same space, and Microformats.)
    Styling
    Behaviour: ECMAScript, the DOM and APIs
    Performance APIs
    Device and System APIs

    Apart from Geolocation it is not clear whether there will be vendor support for the various W3C device related APIs. We will have to wait and see what gets included in browsers and what doesn’t. Or if we have to wait for the next generation.

    Installable Web Application

    Aside from Opera, it isn’t clear if the Widget family of specifications will be adopted by desktop web browsers. There has been some interest on mobile platforms however.

    Graphics, Images and Effects
    Video and Audio
    • video and audio elements in HTML5. Nearest we have to a royalty free codecs at the moment is VP8 for video and OGG Vorbis for audio. Together these make up WebM.
    • WebRTC 1 (includes getUserMedia, which is the replacement for the device element.)
    • Web Audio API
    Fonts
    • WOFF 1, OTF, TTF, SVG Fonts via CSS Web Fonts.
    Other
    What’s Next?

    Its always hard to predict the next era of the Web. Especially when we don’t even fully know how this era will pan out yet. We’re living in an era where web technologies are a realistic option for building applications, especially on mobile where there are so many platforms. PhoneGap is one example of a successful project that allows you to write to the web but deploy as native apps. I think the next era will be when the Open Web has shrugged off Flash and has native apps in its sights. Early skirmishes have already started, but the real titanic battle is yet to begin. Once the Open Web has been super charged with the likes of the Shadow DOM and Component Model, CSS4, WebCL, and access to the full range of device capabilities and services, then the Web will be able to stand shoulder to shoulder with native apps. With the tools at our disposal we should be able to produce user experiences every bit as beautiful, fast and pleasant to use as its native brethren. And don’t forget the server-side, where JavaScript-based technologies such as Node are starting to make their presence felt.

    8 months ago  /  155 notes  /