In the first part of this series, we discussed Backbone.Marionette’s Application. This time around, we’ll discuss the module system that is included in Backbone.Marionette. Modules are accessible through the Application, but modules are a very large topic and deserve an article dedicated to them.
Before we get into the details of how to use Marionette’s module system, we should make sure we all have a decent definition of a module. A module is an independent unit of code that ideally does one thing. It can be used in conjunction with other modules to create an entire system. The more independent a unit of code is, the more easily it can be exchanged or internally modified without affecting other parts of the system.
For this article, that’s about as much as we need to define modules, but if you want to learn more about writing modular code, plenty of resources are on the Internet, of which the “Maintainability Depends on Modularity” chapter of Single Page Apps in Depth is one of the better ones out there.
The JavaScript language doesn’t currently have any built-in methods for defining modules (the next version should change that), but many libraries have arisen to provide support for defining and loading modules. Marionette’s module system, sadly, doesn’t provide support for loading modules from other files, but it does offer some functionality that other module systems do not have, such as the ability to start and stop a module. We’ll cover more of that later. Right now, we will just start with defining a module.
Let’s start with the most basic of module definitions. As mentioned, modules are accessible through the Application, so we need to instantiate one of those. Then we can use its module method to define a module.
var App = new Backbone.Marionette.Application();
var myModule = App.module(‘myModule’);
That’s pretty simple, right? Well, it is, but that’s the simplest module we can create. What exactly did we create, though? Essentially, we told the application that we want a barebones module, with no functionality added by us, and that it will be named myModule (according to the argument we passed into module). But what is a barebones module? It’s an instantiation of a Marionette.Module object.
Module comes with a bit of functionality baked in, such as events (through EventAggregator, which we’ll discuss thoroughly in a later article), starting with initializers (just like Application has), and stopping with finalizers (we’ll go over that in the “Starting and Stopping Modules” section).
Now let’s look at how to define a module with some of our own functionality.
App.module("myModule", function(myModule, App, Backbone, Marionette, $, _){
// Private Data And Functions
var privateData = "this is private data";
var privateFunction = function(){
console.log(privateData);
}
// Public Data And Functions
myModule.someData = "public data";
myModule.someFunction = function(){
privateFunction();
console.log(myModule.someData);
}
});
As you can see, there’s a lot of stuff in there. Let’s look at the top line and work our way down. Just like before, we call App.module and provide a name for the module. But now we’re also passing a function in, too. The function is passed several arguments. I bet you can figure out what they are, based on the names I’ve given them, but I’ll still explain them all:
Module. You’re probably going to want to extend this with some new properties or methods; otherwise, you might as well stick with the short syntax that doesn’t require you to pass in a function.App is the Application object that you called module on.Backbone is, of course, the reference to the Backbone library.Marionette is the reference to the Backbone.Marionette library. It is actually available through Backbone, but this allows you to alias it and make it a shorter name.$ is your DOM library, which will be either jQuery or Zepto (or possibly something else in the future)._ is a reference to Underscore or Lodash, whichever you’re using.After that, you can actually pass in and use custom arguments. We’ll go over this in a bit.
Normally, I would say that most of these arguments are unnecessary; after all, why wouldn’t you already have access to these references? However, I could see these being useful in a couple of situations:
Application object as a dependency. The rest will be available through the arguments given to you by Module.Anyway, let’s get back to explaining the rest of what’s going on in the code above. Inside the function, you can utilize the closure to create private variables and functions, which is what we’ve done. You can also expose data and functions publicly by adding them as properties of myModule. This is how we create and extend our module. There is no need to return anything because the module will be accessible directly through App, as I’ll explain in the “Accessing a Module” section below.
Note: Make sure that you only try to add properties to your module variable and do not set it equal to something (for example, myModule = {…}), because when you set your module variable to something, that changes what the variable’s name is referencing, and none of the changes you specify will show up in your module later.
Earlier, I noted that you can send in custom arguments. In fact, you can send in as many custom arguments as you want. Take a look at the code below to see how it’s done.
App.module("myModule", function(myModule, App, Backbone, Marionette, $, _, customArg1, customArg2){
// Create Your Module
}, customArg1, customArg2);
As you can see, if you pass additional arguments to module, it will pass those in to the function that you are defining your module in. Once again, the biggest benefit I see from this is saving some bytes after minification; other than that, I don’t see much value.
Another thing to note is that the this keyword is available within the function and actually refers to the module. This means you don’t even need the first argument, but you would lose the advantage of minification if you didn’t use the argument. Let’s rewrite that first code using this so that you can see that it’s exactly the same as myModule.
App.module("myModule", function(){
// Private Data And Functions
var privateData = "this is private data";
var privateFunction = function(){
console.log(privateData);
}
// Public Data And Functions
this.someData = "public data";
this.someFunction = function(){
privateFunction();
console.log(this.someData);
}
});
As you can see, because I’m not using any of the arguments, I decided not to list any of them this time. It should also be obvious that you can skip the first argument and just use this.
The final thing I’ll mention about defining modules is that we can split up the definitions. I don’t know exactly why you would want to do this, but someone might want to extend your modules later, so splitting up the definitions might help them avoid touching your original code. Here’s an example of split definitions:
// File 1
App.module("myModule", function(){
this.someData = "public data";
});
// File 2
App.module("myModule", function(){
// Private Data And Functions
var privateData = "this is private data";
var privateFunction = function(){
console.log(privateData);
}
this.someFunction = function(){
privateFunction();
console.log(this.someData);
}
});
This gives us the same result as the previous definition, but it’s split up. This works because in File 2, the module that we defined in File 1 is being given to us (assuming that File 1 was run before File 2). Of course, if you’re trying to access a private variable or function, it has to be defined in the module definition where it is used because it’s only available within the closure where it is defined.
What good is creating modules if we can’t access them? We need to be able to access them in order to use them. Well, in the very first code snippet of this article, you saw that when I called module, I assigned its return value to a variable. That’s because we use the very same method to both define and retrieve modules.
var myModule = App.module("myModule");
Normally, if you’re just trying to retrieve the module, you’ll pass in the first argument, and module will go out and grab that module for you. But if you pass in a function as the second argument, the module will be augmented with your new functionality, and it will still return your newly created or modified module. This means you can define your module and retrieve it all with a single method call.
This isn’t the only way to retrieve modules, though. When a module is created, it is attached directly to the Application object that it was constructed with. This means you can also use the normal dot notation to access your module; but this time, it must be defined beforehand, otherwise you’ll get undefined back.
// Works but I don't recommend it
var myModule = App.myModule;
While this syntax is shorter, it doesn’t convey the same meaning to other developers. I would recommend using module to access your modules so that it is obvious you are accessing a module and not some other property of App. The convenience and danger here is that it will create the module if it doesn’t already exist. The danger comes if you misspell the name of the module; you won’t have any way of knowing that you didn’t get the correct module until you try to access a property on it that doesn’t exist.
Modules can also have submodules. Sadly, Module doesn’t have its own module method, so you can’t add submodules to it directly, but that won’t stop us. Instead, to create submodules, you call module on App, just like you used to do; but for the name of the module, you need to put a dot (.) after the parent module’s name and then put the name of the submodule.
App.module('myModule.newModule', function(){
...
});
By using the dot separator in the module’s name, Marionette knows that it should be creating a module as a submodule of the module before the dot. The cool (and potentially dangerous) part is that if the parent module isn’t created at the time that you call this, it will create it along with its submodule. This can be dangerous because of the same potential for misspelling that I mentioned earlier. You could end up creating a module that you didn’t intend to create, and the submodule would be attached to it, instead of to the module you intended.
As before, submodules can be accessed the very same way they are defined, or you can access them as properties of the module.
// These all work. The first example is recommended
var newModule = App.module('myModule.newModule');
var newModule = App.module('myModule').newModule;
var newModule = App.myModule.newModule;
// These don't work. Modules don't have a 'module' function
var newModule = App.myModule.module('newModule');
var newModule = App.module('myModule').module('newModule');
Any of these methods of accessing the submodule will work equally well if both the module and submodule have already been created.
If you read the previous article in the series, about Application, you will know that you can start an Application with start. Well, starting modules is the same, and they can also be stopped with stop.
If you recall (assuming you’ve read the previous article), you can add initializers with addInitializer to an Application, and they will be run when it is started (or will run immediately if the Application has already started). A few other things happen when you start an Application. Here are all of the events, in order:
initialize:before event,initialize:after event,start event.A Module behaves in a very similar way. The number of events and some of the names of the events are different, but overall it is the same process. When a module is started, it:
before:start event,start event.The stop method is also very similar. Instead of adding initializers, though, you need to add finalizers. You do this with addFinalizer and by passing in a function to run when stop is called. Unlike with initializers, no data or options are passed along to each of the functions. When stop is called, it:
before:stop event,stop event.Initializers and finalizers aren’t only meant for use by others. In fact, they are quite helpful when used inside the module definition. This way, you can define a module inside the definition without actually creating any objects to be used, but then write your initializers to start creating the objects and setting them up, such as in the example below.
App.module("myModule", function(myModule){
myModule.startWithParent = false;
var UsefulClass = function() {...}; // Constructor definition
UsefulClass.prototype ... // Finish defining UsefulClass
...
myModule.addInitializer(function() {
myModule.useful = new UsefulClass();
// More setup
});
myModule.addFinalizer(function() {
myModule.useful = null;
// More tear down
});
});
When a module is defined, by default it will automatically start at the same time that its parent starts (either the root Application object or a parent module). If a module is defined on a parent that has already started, it will start immediately.
You can set up a module to not start automatically by changing its definition in one of two ways. Inside the definition, you can set a module’s startWithParent property to false, or you can pass an object (instead of a function) to module that has a startWithParent property set to false and a define property to replace the normal function.
// Set 'startWithParent' inside function
App.module("myModule", function(){
// Assign 'startWithParent' to false
this.startWithParent = false;
});
// -- or --
// Pass in object
App.module("myModule", {
startWithParent: false,
define: function(){
// Define module here
}
});
App.start();
// myModule wasn't started, so we need to do it manually
App.module('myModule').start("Data that will be passed along");
Now the module won’t autostart. You must call start manually to start it, as I did in the example above. The data that is passed to start could be anything of any type, and it will be passed along to the submodules when they’re started, to the initializers, and to the before:start and start events.
As I said, data isn’t passed along like this when you call stop. Also, stop must be called manually, and it will always call stop on submodules; there is no way around this. This makes sense because a submodule shouldn’t be running when its parent isn’t running, although there are cases when a submodule should be off when its parent is running.
I mentioned that Module comes with some baked-in functionality, such as the EventAggregator. As discussed, we can use the on method on a module to watch for events related to starting and stopping. That’s not all. There are no other built-in events, but a module can define and trigger their own events. Take a look:
App.module('myModule', function(myModule) {
myModule.doSomething = function() {
// Do some stuff
myModule.trigger('something happened', randomData);
}
});
Now, whenever we call doSomething on the module, it will trigger the something happened event, which you can subscribe to:
App.module('myModule').on('something happened', function(data) {
// Whatever arguments were passed to `trigger` after the name of the event will show up as arguments to this function
// Do something with `data`
});
This is very similar to the way we do things with events on collections, models and views in normal Backbone code.
The modules in Marionette can definitely be used to define modules very similarly to any other module definition library, but that’s actually not how it was designed to be used. The built-in start and stop methods are an indication of this. The modules that Marionette includes are meant to represent somewhat large subsystems of an application. For example, let’s look at Gmail.
Gmail is a single application that actually contains several smaller applications: email client, chat client, phone client and contact manager. Each of these is independent — it can exist on its own — but they are all within the same application and are able to interact with one another. When we first start up Gmail, the contact manager isn’t up, and neither is the chat window. If we were to represent this with a Marionette application, each of those sub-applications would be a module. When a user clicks the button to open the contact manager, we would stop the email application (because it becomes hidden — although, for speed, we could keep it running and just make sure it doesn’t show in the DOM) and start the contacts manager.
Another example would be an application built largely out of widgets. Each widget would be a module that you can start and stop in order to show or hide it. This would be like a customizable dashboard such as iGoogle or the dashboard in the back end of WordPress.
Of course, we’re not limited to using Marionette’s modules in this way, although it’s difficult to use it in the traditional sense. This is because Marionette’s modules are fully instantiated objects, while traditional modules are “classes” that are meant for instantiation later.
Phew! That’s a lot of information. If you’ve made it this far, I commend you (although it was much easier for you to read this than for me to write it). Anyway, I hope you’ve learned a lot about the way that Marionette handles defining, accessing, starting and stopping modules and submodules. You may find it to be a very handy tool, or you might choose to completely ignore its existence. That’s one of the great things about Backbone and Marionette: most of their features are largely independent, so you can pick and choose what you want to use.
Credits of image on front page: ruiwen
(al) (ea)
© Joseph Zimmerman for Smashing Magazine, 2013.
Earlier this year, I was in the beginning stages of a redesign for our company’s website. We had already been planning to use a straightforward responsive approach to Web design, which is our preferred solution for multi-device support. After hearing some frank discussions at An Event Apart conference in Boston about the limitations and challenges of responsive Web design, I realized that our solution needed a bit of adjustment.
Thankfully, the project before us was the ideal opportunity to experiment and push ourselves to improve our responsive workflow. In this article, I will detail the process we took, including some of the changes we made along the way, as we worked to build a better responsive website.

The variety of devices being used to access our websites is more diverse than ever. (Image: Blake Patterson)
The first step in our project was to make a list of the benefits and drawbacks to the responsive approach we had been using. Our list looked like this:
What you will likely notice here is that the drawbacks we identified with a responsive approach are areas where a mobile-only solution excels. We wanted the best of both worlds for our new website — the advantages that a responsive approach and a mobile-specific solution have to offer.
One of the common differences between a responsive design and a dedicated or mobile-only design is in the content or features that are delivered to the browser. A mobile-specific website often features only a subset of content found on the “normal” version of the website. This is one of the ongoing debates about the two approaches, and proponents of mobile-only websites often argue that mobile users want access only to content that is “important” to them.
The problem with this line of thinking is that what is “important” to a user — any user — changes according to their situation. Eliminating access to content based solely on the device someone is using is sure to alienate and frustrate anyone who doesn’t fit into the ideal scenario that you envisioned when you decided what to include in and what to eliminate from your mobile website.
Our belief has always been that all users should have access to all of the content that the website has to offer, but we wanted to make sure this was indeed the right answer for our website and our users. To help us determine the right approach, we turned to our analytics and found no discernible difference between the type of content requested by our mobile visitors and by our visitors on non-mobile devices. Content that was popular for desktop users was similarly popular for mobile visitors.
Additionally, we sat down and spoke with some of our current clients, who represent a large part of our website’s audience, and asked them some questions, including “What content are you coming to our website for when on a desktop computer?” and “How about on a tablet or a phone?” The interviews were obviously more in depth than this, but you can see what we were asking. Once again, we found that the content they were seeking was the same, regardless of the device they were using.
The findings from our research reinforced our belief that a responsive approach, which provides access to the same content across all devices, was the right choice for our website. This research also enabled us to determine what content on our website was not being accessed at all. When we discovered pages that were not being used by our audience, we cut them from our site map. Similarly, content that was most popular was treated appropriately in our content hierarchy and our layout plans for the redesign.
By starting the project by looking at our content and gathering data on what was important to our audience and what was not, we were able to move into the design phase with an informed plan for what content our website’s design needed to support.
I have heard the arguments for designing in the browser, and I appreciate many of the benefits this approach brings. That being said, having tried designing in the browser on a number of occasions, I have found that my own design workflow is simply better suited to starting in Photoshop. In no way do I think this is the right decision for everyone, but it is the right decision for me, and it is how I began this design.
For responsive designs, I use a method that I refer to as “designing to the extremes.” I start by designing the desktop version of the website. In this version, I work out the design’s typography, tone and overall visual direction — as well as the layout for the large screen view of the website. Once I am happy with this version of the design, I work on the small screen or “mobile” version of the website, using the same visual direction, but adjusting the layout as appropriate for the smaller screen.
At the end of this process, I have visual examples of the two layouts of the website that will vary the greatest — the biggest and the smallest screen versions of the design. These two examples will guide me as I begin the website’s front-end development.

The “extreme” versions of the new website design
The “mobile-first” approach to responsive design is not a new idea. This method, whereby you build the mobile experience and layout of a website first and then use media queries to adjust and add to that layout as the screen size grows, has been considered a best practice in responsive Web design for some time now. While not a new approach, it is still an important one, and coupled with our plan to “start with the content,” it helped us to address one of the shortcomings that we identified in our responsive projects — the problem of delivering unnecessary content.
By starting with content, we ensured that all of our website’s content was relevant and appropriate to all users, mobile or otherwise. This meant that we didn’t have to worry about delivering large amounts of content in the markup only to have to hide it visually with CSS. The mobile-first approach meant that images would be delivered only to devices they are intended for. For instance, our new design called for a background graphic of a watercolor texture.
The image, which is quite large, is intended to be a part of the design only on larger screens (660 pixels and up). Because our CSS starts with the mobile design first, this large graphic is never sent to small-screen devices because the media query that loads the image is activated only by larger screens. That media query, which applies the background to our html element, looks like this:
@media only screen and (min-width: 660px) {
html {
background: url(/images/bg-watercolor.jpg) no-repeat fixed center top;
}
}
In addition to adding that background image, this media query that is triggered at 660 pixels also introduces a number of other layout changes to the website, transitioning from what we consider the small-screen layout to what will become the various larger-screen versions.
When we began using responsive design in our Web projects, we focused on known devices and screen sizes, and our media queries often reflected those known devices (iPhones, iPads in both portrait and landscape orientation, laptops, widescreen desktops, etc.). Over time, we found that this was not the best approach because it only addressed the devices and screen sizes that were popular today and not those that may come in future. One of the strengths of responsive Web design is its future-friendly aspect. So, to fully realize that strength, we moved away from building to devices, instead allowing the design to dictate our media query breakpoints.
The mobile-first method established the baseline for our website’s CSS. With that in place, we launched the website in a browser and scaled it to the smallest size of our layout (we set a minimum width of 320 pixels in the CSS). Slowly, we increased the size of our browser window to see how the layout responded. As the browser window widened, we noticed that the layout began to feel strained. It was at these points that we would need to establish a new media query to adjust the layout.
To help us with this approach, we created a graphic and set it as the background of our desktop. With vertical lines showing us a width of 320 pixels (our smallest size) and then a break at every hundred pixels starting with 400, we used this as a guide as we scaled the browser window to determine where the design started to break down, and then used those approximate pixel values in the resulting media queries that we added to the CSS.

This desktop background can be used to help determine the breakpoints needed for a responsive design.
This approach of adding media queries based on the needs of the design, rather than on known device sizes, enables a website to better respond to a wider range of screen sizes. It does, however, end up filling the CSS file with more media queries than if you were using device-specific breakpoints. Still, while the number of media queries is higher, the queries themselves tend to be very small because you are making few changes with each one, rather than making the sweeping changes normally needed for device-specific media queries.
One area of our website where this increase in media queries is evident is the navigation.
Handling navigation is one of the most challenging aspects of responsive design. For our website, we essentially have four main areas of navigation.
Because our CSS is mobile-first, one of the first things we did was to establish the navigation for our small-screen layout. This meant turning off the display of all of the navigation sections expect for the primary navigation.
#helpNav, .subNav, footer nav {
display: none;
}
Now, I said earlier that our goal was not to deliver content to devices only then to “turn it off.” That was indeed the goal, but with our navigation, we had to accept that this was how we needed to do it. We weren’t able to find another, simple yet maintainable, solution. Luckily, the content we are delivering and not displaying turns out to be only a few lists, so the impact on downloading for visitors is minimal.
The help navigation is the one area of the website that has been considered to be not relevant to most users, because these links and portals are intended only for desktop users. Now that’s a big assumption and a bold statement. The rationale behind this was that the portals themselves, which are all third-party applications over which we have no control, are not optimized for very small-screen mobile devices, and the services they offer are geared to supporting corporate clients with large screens on desktops.
This situation informed our decision to remove that section from the small-screen version and in the months that the site has been live we received no comments or complaints from our user base regarding that decision. For the other two navigation areas, our subpage section navigation and our footer navigation, this content is presented as part of the primary navigation for small-screen devices. This is why we turn off these three areas by default.
Later, as the screen size increases and we get past the 660-pixel point where the larger-screen design begins to show, we will style these navigation areas as needed.
Here is the CSS for our help navigation:
#helpNav {
display: block;
position: absolute;
top: 1px;
right: 0px;
width: 100%;
text-align: right;
}
#helpNav ul {
padding-left: 10px;
}
#helpNav li {
display: inline;
padding-right: 6px;
padding-left: 6px;
background-color: #2f6a98;
}
#helpNav a {
font-size: 12px;
padding: 0 6px;
color: #FFF;
border-radius: 20px;
}
#helpNav a:hover {
background-color: #f66606;
}
And our subpage navigation areas:
.subNav {
display: block;
width: 25%;
float: left;
}
.subNav h4 {
padding-bottom: 8px
}
.subNav ul {
list-style: disc;
color: #c65204;
padding: 0 0 20px 20px;
}
.subNav li {
padding-bottom: 14px;
}
.subNav a {
color: #186483;
font-size: 21px;
font-family: 'RokkittRegular', Times, "Times New Roman", serif;
line-height: 1;
}
Finally, our footer navigation:
footer nav {
display: block;
margin-top: 40px;
}
footer nav ul {
list-style: none;
}
footer nav li {
padding-bottom: 24px;
width: 19%;
padding: 0 5% 20px 0;
float: left;
}
.innerNav li {
width: 100%;
float: none;
padding-bottom: 4px;
}
footer nav a {
color: #575454;
font-size: 12px;
}
.innerNav a {
font-weight: normal;
}
You will notice that we have used pixel values in our media queries. Using pixel-based media queries is how we, like many front-end developers, began implementing responsive design, and we have maintained the practice as part of our responsive workflow. In the spirit of “building a better responsive website,” though, I’ll point out an article on proportional media queries using ems that was brought to our attention during the editing of this piece. Essentially, to improve the appearance of the site when zoomed in, it’s highly recommended to convert px-media queries into em-media queries by dividing all pixel values by the body font-size.
This wonderful article has caused us to rethink our pixel-based approach to media queries, and it is another example of how we continue to refine our responsive approach. While we did not use ems in our media queries in this particular project, we are experimenting with them now, and the approach is worth mentioning here.
Our primary navigation is presented on wide screens as a horizontal row across the top of the layout. On small screens, this primary navigation structure changes so that there is a large “Menu” button at the top of each page that links to the navigation at the bottom of the page. To accomplish this, we added a link with an ID of menuLink and a class of tabButton in the header, which is near the start of the markup. We then placed a division with an ID of mainNav at the very end of the markup. Inside that division is our main navigation, which is simply an unordered list with a number of other unordered lists inside it for the subpage section menus. We also have another anchor with an ID of toTop, which acts as a link back to the top of the page.

The small-screen layout presents a “Menu” button at the very top of the layout.
Continuing our mobile-first approach, we styled the menu link at the top of the small-screen layout to look like a button.
#menuLink a {
float: right;
margin: -56px 8px 0 0;
}
.tabButton a {
color: #FFF;
font-family: 'RokkittRegular', Times, "Times New Roman", serif;
font-size: 20px;
background-color: #45829b;
padding: 10px 12px;
border-radius: 10px;
}
.tabButton a:hover {
background-color: #f66606;
}
Our main navigation menu is set to its small-screen display:
#mainNav {
margin-top: 30px;
width: 100%;
}
#mainNav #toTop a {
float: right;
margin: 0 8px 0 0;
font-size: 20px;
}
#mainNav nav {
padding-top: 80px;
}
#mainNav ul {
list-style: none;
}
#mainNav li {
background: #45829b;
border-bottom: 1px solid #abc7d2;
padding: 4px 10px 4px 15px;
}
#mainNav li:hover {
background-color: #f66606;
}
#mainNav a {
font-size: 24px;
color: #FFF;
font-family: 'RokkittRegular', Times, "Times New Roman", serif;
}

Our website’s primary navigation as presented for small-screen layouts
Our submenus, which are set not to display initially, we can now display as the page requires. Each of these submenus has a unique ID, such as servicesTab, and each section of the website has a class applied to the body tag. The class for the “Company” section is companyPage. We use this class to set styles for that entire section of the website. We use the class of the submenu sections to turn on the submenus as needed when a section is active.
.companyPage #companyTab ul,
.newsPage #newsTab ul,
.contactPage #contactTab ul,
.servicesPage #servicesTab ul {
display: block;
}

The subpage navigation displayed for the small-screen layout
As the larger-screen layouts kick in — once again with the media query for 660 pixels and above — we dramatically change the primary navigation’s layout. First, we turn off the display of the menuLink and toTop buttons because they are no longer needed:
#menuLink a, #toTop a {
display: none;
}
Next, we style the mainNav horizontally across the top of the page to achieve the larger-screen design:
#mainNav {
position: absolute;
top: 92px;
margin: 18px 2% 0 2%;
width: 96%;
text-align: center;
}
#mainNav nav {
padding: 5px 0;
border-top: 1px solid #bacfd7;
border-bottom: 1px solid #bacfd7;
}
#mainNav li {
background: none;
display: inline;
border-bottom: 0;
border-right: 1px solid #bebebe;
padding: 0 6px 0 8px;
margin: 4px 0;
}
#mainNav a {
font-size: 16px;
color: #45829b;
}
#mainNav a:hover {
color: #f66606;
}
These styles set the look of our primary navigation. But to build to the design, instead of to the device, we will need to make small adjustments as the screen size grows. Our primary navigation’s font has eight different sizes in total for the larger-screen layouts, changing as the screen grows and as we have more room to work with. Figuring out how best to display this navigation so that it is both easy to use and visually attractive was one of the challenges we faced while working with this responsive design.
Initially, our font size is set to 16 pixels. Once we hit 767 pixels in width, we bump that to 18 pixels.
@media only screen and (min-width : 767px) {
#mainNav a {
font-size: 18px;
}
}
We continue this pattern a number of times, increasing the font size finally to 27 pixels as the website reaches its largest size. In this way, the website’s navigation truly responds best to the design and to the screen being used to view that design.
Our preferred CMS is ExpressionEngine, and the specifics of this next portion of the article refer to that platform, but the general idea of what we accomplished with ExpressionEngine could undoubtedly be applied to other popular CMS platforms as well.
One of the biggest drawbacks to the responsive approach is that you cannot deliver different markup or a different source order to different devices. This drawback is what we wanted to overcome with our CMS. During our experimentation and research, we stumbled upon an article titled “Going Truly Adaptive With ExpressionEngine.” Using the approach detailed in this article, we were able to use a device-detection script to set a variable in the system of either mobile or full. We could then conditionally load markup into our website based on which of these variables was met.
By going further and using the device detection, we were able to make other very small changes to
further improve the mobile experience. To us, this was kind of like progressive enhancement, where we created a quality solution and then tried to take it further to deliver a slightly more optimized experience.
Make sure to read Chris Coyier’s similar view on combining RWD and mobile templates in which he argues about mixing and matching a variety of techniques for your mobile strategy.
You could certainly use these variables to deliver completely different markup and source orders to different devices, but our initial approach was a little less extreme. Because we had already decided that all versions of our website would have access to all content, we initially used this variable method to make slight adjustments to how much of that content would be delivered. For instance, on our website’s home page, we show teasers for a variety of content found within the website. For the “Culture” and “Project Spotlight” sections, an image accompanies each post.
The images are a nice-to-have addition but certainly not critical, so we do not deliver these images to mobile users at all. Now, I do not mean that we use CSS to turn off their display, which would cause the data to get delivered to the browser anyway; instead, we use the variables we have established to omit the images from the markup unless they need to be shown.

The teaser images are nice to have, but not critical to the content or layout.
The syntax is quite easy. Once you have established your variables — which the aforementioned article explains how to do easily by adding a little script to the system’s config.php file — you can use those variables like an if statement.
{if global:site_version=='full'}<img src="{teaser-image}" alt="Building A Better Responsive Website" />{/if}{if global:site_version=='mobile'} Building A Better Responsive Website{/if}
This is ExpressionEngine syntax, but you should be able to read this and easily see what is happening. If the full variable is met, then we deliver the teaser-image from that article’s entry in the database. If the mobile variable is met instead, then we deliver the title of the article.
We use this same approach for the home page’s “News” and “Blog” sections, delivering three short teasers if the full variable is met and only one if the mobile one is. That syntax looks like this:
{exp:channel:entries channel="news" {if global:site_version=='full'}limit="3"{/if}{if global:site_version=='mobile'}limit="1"{/if}}
Here you see that we are accessing the ExpressionEngine channel named news. We use our variable to determine how many recent entries will be displayed from that channel, using the limit parameter.
In the website’s “Culture” section, we publish articles that are often accompanied by a number of images. Unlike the teaser images on the website’s home page, the images in the articles themselves are critical to that content, because they help to carry or reinforce the article’s point. Now, while the images are important, they are also quite large — each one is 650 pixels wide, and most articles include at least three images and as many as ten. Because mobile devices will show the images at about half their original size, the downloads for the full-sized images would be quite substantial. To address this, we once again turned to our device detection and variables.
For each article, we produce two sets of images: one full sized at 650 pixels wide and a second set at almost half that size. We then use the variables in our article (but first we need to allow ExpressionEngine code in our page’s template), and we include the markup for both sets of images — but only one set is ever delivered to the browser. Mobile devices get the smaller images, while everything else gets the normal set.
We take a similar approach with the home page’s large billboard area. These rotating banner messages and images are used to promote important items, such as upcoming events, new services and announcements, in a bigger way than we do in the other areas of the home page. The billboard is another nice-to-have element that is intended for large displays only. Once again, we use the variables to deliver the main billboard division, as well as the JavaScript that runs it, to appropriate devices — effectively enabling us to send different markup to different devices and eliminating yet another of the drawbacks that we identified at the start of this project.
Through a mobile-first approach and with our CMS’ help, we are able to deliver our home page to desktop users at 738.3 KB and dramatically reduce that to only 174.4 KB for mobile users.
One of the questions that has always bothered me about a mobile-only approach and device detection is, What happens if that detection fails? Is the “normal” version of the website delivered to the mobile device, thereby rendering your carefully designed mobile experience null and void? This possibility is one of the main reasons why I have avoided a mobile-only solution that uses device detection in the past.
For our new responsive workflow, we are using device detection, but our process has equipped us with excellent fallbacks in case that detection fails for some reason. Because we are using a responsive approach, even if the full version get delivered to a mobile browser, the layout will be suited to that device because our CSS will adjust the website’s layout accordingly.
Additionally, because we went with a mobile-first build, items not intended for small screens, such as the giant background graphic mentioned above, do not get delivered either. The only thing that will fail is what we have done with our device detection-generated variables. If the worst-case scenario happens and our detection fails, then the mobile version would simply get a few extra images or a little markup or JavaScript that it does not need. The experience would still be suited to mobile. Not bad at all for a “worst-case scenario.”
A few years ago, a client said something to me that has stuck with me to this day. Talking about his website, he said:
“Don’t worry about making my website perfect. Just work on making it better. If we’re constantly making it better, we’re going in the right direction.”
This idea has guided me over the years and reminded me never to dismiss a better solution simply because it is not perfect.
I know this is not a perfect solution, and I am OK with that because it is an improvement to our previous responsive workflow. It has helped us overcome some obstacles that we identified, and we can now bring those improvements to other projects we are working on. Yes, there are still many issues that we have yet to effectively address, such as the delivery of higher-quality images to HD displays as well as the use of em-based media queries referred to earlier in this piece, but we are moving in the right for this project and for others.
Who knows? Maybe someday someone will build a “perfect website.” In the meantime, we will focus on progress, not perfection, as we continue to make small improvements along the way, working to build a better responsive website.
(al)
© Jeremy Girard for Smashing Magazine, 2013.
As UI designers, we’re always interested in learning, reading user research, understanding best practices and keeping up to date on all the latest approaches and tactics for building websites and applications.
One of the most exciting concepts we’ve started to apply to our thinking is the mobile-first approach, famously pioneered by designer Luke Wroblewski on his blog and then in his subsequent book. Generally, this approach provides a healthy way to gain focus, cut the fat and get to the heart of what’s important — for both content and interaction.
But what happens if you have an existing site or app that was built for desktop without a responsive or mobile strategy in mind? And more specifically, what if you, like us, don’t have the resources, time, or budget to start over from scratch in the near term? Despite being a design shop, we at Fresh Tilled Soil found ourselves in this very position. This is how we addressed it.
As a Web and mobile app UI design firm, we couldn’t very well ignore the problem for much longer and let prospective clients pinch, zoom, and squint on their phones to assess whether we were the right agency for them — particularly when we offer mobile Web and native app design services!
So what to do? A design firm offering mobile and responsive design solutions should certainly practice what it preaches – especially with the data showing an increasing number of visitors accessing our site from their smartphones. Because we wanted to share the same information regardless of device type and maintain a single codebase, a responsive approach was the best solution.
Though our resources were limited, we were fortunate enough to have several team members with a limited window of upcoming availability. We quickly assembled a small team with the goal of rapidly making our entire website truly responsive (though keeping a particular eye on our iPhone and Android users). Based on our analytics reports, these devices were by far the most popular among viewers of our site.
Our research showed us that 51% of mobile visits were on iPhones, 40% were on iPads and the remaining 9% was broken up between various Android smartphones and tablets. However, we felt that a truly responsive solution where each of our layouts was fluid made for a better solution than just targeting specific devices.
Consider the limited real estate of a mobile screen and examine ways to simplify layouts.
In designing for the mobile experience, the first decision we made was to simplify the navigation to a series of icons that represented each of the sections. We removed the large background image of our handsome CEO, Richard Banfield, and focused on making it easy to see the positioning statement and start any of the videos.
Think about what visitors want most from your mobile website and consider how to make it easy for them to access.
We thought it was important for clients who were visiting us for the first time to be able to easily contact us or access a map to our location. By envisioning this from the user’s perspective, we decided this content was important enough to be in a prominent location on mobile devices. Simply showing this section when the device screen width implied a mobile resolution and setting it to not display on larger screens was enough to do the trick.

Contact information and directions were made more prominent in the layout for small screens, to assist clients who are visiting for the first time.
Make sure your interactions work smoothly on smaller screens and retain their context.
The portfolio section was simplified on smaller devices to only showcase six projects, and the portfolio detail images now appear above the thumbnails rather than over them to keep the context of the portfolio section.

Interactions were simplified to make sure they would work smoothly on smaller screens.
If something requires a custom design approach, invest the time to truly optimize it.
Some UI choices that make great sense on a desktop simply fall flat on a mobile screen. On the desktop version of our website, the team bios slide into view above a grid of team members, with each person’s details appearing to the left of a larger head shot. Knowing that these biography layouts would probably have to anchor and jump much higher than the grid and would then require quite a bit of scrolling to read the bio, we came up with an altered design treatment that resembles a modal overlay.

UI approaches that didn’t work well on small screens were given a different design treatment.
It was important to identify that the team section would need custom design early in the process so we could get started designing, testing and iterating. We used a div that slides up from the bottom of the page, covering about 90% of it. The bios were then shortened in length so that each bio could be presented without scrolling in both the portrait and landscape orientations on our target devices.
Not every layout needs to be re-designed for a smaller screen. Sometimes making columns stack and letting their widths fit the screen is the optimal treatment.
On our website, not all sections required custom treatments for smaller screens. Below the team area, the “Habitat” (article, workshops and events) section implements a more straightforward responsive approach in which the two-column layout simply stacks vertically. The detail pages for each of those items also use a similar stacking approach, and we made sure the option to register for a workshop was in a prominent location.
Always consider simplifying. If something on your desktop website doesn’t apply to a mobile context, then maybe you can remove it. If you find it’s an improvement, then consider ways to simplify the desktop layout as well.
Toward the bottom of the page, our contact section was greatly simplified to only include a mobile-friendly contact form for prospective clients to get in touch. Since we already feature the “call us” and “directions” buttons at the top of the website, we were able to remove the address and map from this section.

The contact section was simplified to remove duplicate elements.
Since launching the responsive version of our website, we’ve noticed the following improvements in mobile user behavior:
Additionally, we’ve received several compliments from prospective clients who have accessed our website for the first time using their phone.
While a mobile-first approach gets to the heart of simplifying a site or interface for all resolutions, large and small, that just is not always possible. In a crunch, we feel the process we undertook helped greatly improve our site on smaller devices. And in the process, it made us even more knowledgeable about supporting various devices with a single codebase.
(cp) (ea)
© Alex Fedorov for Smashing Magazine, 2013.
Everyone likes stuff that moves about on the Web, right? Remember how you cried joyful tears when you first used <marquee>? I do. I nearly sobbed all the water out of my body as I gazed upon “JAKE’S COOL WEBSITE” bobbing back and forth in uppercase serif. Of course, we’re more mature as an industry these days.
We’ve learned that users don’t want websites to look like a CSI console having a personal crisis; instead, we go for smooth transitions that enhance the experience, rather than being the experience themselves. In terms of animation APIs, we’ve been poorly catered to, leaving us to hack around with timers that weren’t really built for animation. Things have been steadily improving in that area, but the new Web Animation specification looks set to shake things up a lot.
So, why do we need a new animation spec? Don’t we have enough ways to animate things already?

Optimizing the way to makes things move.
Imagine we wanted to animate something horizontally from one left position to another, over three seconds, and then do something on completion. We can do this without JavaScript, using CSS animations, but if the start and end positions are programmatically determined, then we’ll need something that we can control from script.
requestAnimationFrameIf you’re performing visual updates with JavaScript, then you should be using requestAnimationFrame. It synchronizes itself to real screen updates, giving you as much time as possible to get everything ready for rendering. If the browser is on a 60 Hz screen (most are) and your frames can be constructed in less than a 60th of a second, then you’ll get 60 frames per second (FPS). requestAnimationFrame prevents you creating frames that don’t have time to display. Synchronizing to the screen’s rate is important; 30 FPS looks smoother than 40 FPS because 40 doesn’t divide into the screen’s native 60 Hz. HTML5 Rocks has a great article on syncing to the screen.
Unfortunately, jQuery uses setInterval, which isn’t as smooth as requestAnimationFrame. requestAnimationFrame doesn’t trigger while the tab or window isn’t visible, which is A Good Thing. Unfortunately, this has created backwards incompatibility with websites that rely on setInterval’s less optimal behavior of continuing to run in the background. You can opt into requestAnimationFrame via a plugin. Go and add that to all of your pages using jQuery animation now — I promise to wait for you — just make sure that switching tabs doesn’t break your animations.
Anyway, enough chatting. Here’s a simple animation using raf, moving a box horizontally from 250px to 500px. Note that the box starts at 0px, so there’s a jump to 250px when the animation starts; this proves we can start the animation from a point other than its current rendered position.
Here’s the code:
// On button press…
animateLeft(elm, '250px', '500px', function() {
console.log("Done!");
});
// The implementation
function animateLeft(elm, from, to, done) {
// Turn our CSS values into numbers
// We're being lazy and assuming they're in px
from = parseInt(from, 10);
to = parseInt(to, 10);
// Work out the amount we need to move the box
var diff = to - from;
var duration = 3000;
var startTime = performance.now();
// Set initial position
elm.style.transform = 'translate(' + from + 'px, 0)';
function frame(time) {
// How long has the animation been running?
var animTime = time - startTime;
// Are we done?
if (animTime >= duration) {
// It's likely that the last rendered position wasn't the
// final position, so we set it here.
elm.style.transform = 'translate(' + to + 'px, 0)';
done();
}
else {
// What position should the box be in?
var position = from + (animTime / duration * diff);
elm.style.transform = 'translate(' + position + 'px, 0)';
// Request our next frame
requestAnimationFrame(frame);
}
}
// request our first frame
requestAnimationFrame(frame);
}
The above is the ideal according-to-specification code. In the working example, I had to deal with vendor prefixes on requestAnimationFrame and transform. We’re animating using transform and translate, rather than left, because they allow for subpixel positioning and, therefore, smoother animation, one of the advantages that Flash had over HTML for so long.
This is a pretty large and stinky chunk of code to simply animate a thing, and it would get a lot larger if we handled differing CSS units and easing. Of course, you could stick all of the complicated bits in a library and give yourself a simpler API. Here’s the frame-by-frame breakdown:
This is the timeline view of Chrome Developer Tools while the animation is running. Each frame executes some JavaScript, recalculates the style and layout, paints the box, and then sends that to the GPU, which composites it to the page. The draw time spikes a few times, resulting in a jolt in the animation. This is caused by delays in interacting with the GPU (the gray spikes) or delays caused by other JavaScript (the yellow spikes).
This highlights a performance bottleneck of JavaScript-driven animation:
Here, another bit of JavaScript does some stuff and takes 250 milliseconds to do it. While this is happening, our animation can’t move. In the real world, this could be a social-media button waking up and doing something slow, or it could be some of your own script triggered by a user interaction. In the example above, I made a button that performs a while loop for 250 milliseconds (I’m pretty sure this code is in every social-media button). If you press it during the animation, it will block the animation and look nasty.
I recently sung the praises of requestAnimationFrame for animating canvas, so why am I hatin’ on it now? JavaScript-driven animations aren’t a bad practice — they give you full control frame by frame and pixel by pixel when combined with <canvas> — but returning to JavaScript land 60 times a second is overkill for DOM animations that have a defined start and end. Ideally, we want to tell the browser all about our animation and leave it to do its thing, while we get on with something else.
Of course, we kinda have this already.
.whatever {
transform: translate(250px, 0);
transition: transform 3s linear;
}
.whatever:hover {
transform: translate(500px, 0);
}
CSS transitions and animations let the browser make all kinds of optimizations because it knows the end point of the animation. They’re not blocked by JavaScript on some platforms, such as Chrome for Android and desktop Chrome with threaded compositing enabled in about:flags (expect threaded compositing to arrive in more browsers).
Let’s script it!
function animateLeft(elm, from, to, done) {
// Set initial position
elm.style.transform = 'translate(' + from + ', 0)';
// Define the transition type
elm.style.transition = 'all 3s linear';
function transitionEnd(event) {
// Beware of bubbled events
if (event.target != elm) { return; }
// Clear the transition
elm.style.transition = '';
// We don't want that listener firing for future anims
elm.removeEventListener('transitionend', transitionEnd);
done();
}
// Listen for end of transition
elm.addEventListener('transitionend', transitionEnd);
// start the transition
elm.style.transform = 'translate(' + to + ', 0)';
}
Here’s a live example. It’s much simpler than our raf example, but a bug has crept in. The from is ignored; the animation starts from the element’s current position, even though we’ve explicitly set it to something else. Why?
// Set initial position
elm.style.transform = 'translate(' + from + ', 0)';
// Define the transition type
elm.style.transition = 'all 3s linear';
// …and later…
// Start the transition
elm.style.transform = 'translate(' + to + ', 0)';
Changing properties in the style object doesn’t change the element’s computed style. The style is computed only when the browser needs to know the impact that those styles will have on the page (for example, when the element needs to be drawn). The element doesn’t need to be drawn between the two assignments to elm.style.transform, so the first assignment is ignored.
Of course, we can hack it:
// Set initial position
elm.style.transform = 'translate(' + from + ', 0)';
// Abracadabra!
elm.offsetWidth;
// Define the transition type
elm.style.transition = 'all 3s linear';
// …and later…
// start the transition
elm.style.transform = 'translate(' + to + ', 0)';
offsetWidth returns the rendered width of an element, including padding. To calculate this, the browser needs to take into account all of the styles on the page, including the transform that we set for the initial position. That works. Check out the live example.
Performance is steady at 60 FPS. And we can see that each frame is a simple composite; all of the heavy lifting is farmed out to the GPU.
However, relying on offsetWidth to force the element into its starting position is hacky, and it’s conceivable that a future browser release will find a way to optimize out the reflow, breaking our hack.
Reflows are not without cost either:
The Developer Tools warn us about this use of offsetWidth, because the browser calculates a layout that it never draws. The test page is very basic, so the layout cost is cheap, but things can be very different in the real world.
So, is there a less hacky, more reliable way?
CSS animations have explicit keyframe values. Let’s script them:
function animateLeft(elm, from, to, done) {
// Create a style element for our animation
var style = document.createElement('style');
// Generate a unique name
var animName = 'anim' + Date.now() + Math.floor(Math.random() * 10000);
// Build the CSS
style.textContent = '' +
'@keyframes ' + animName + ' { ' +
'from { ' +
'transform: translate(' + from + ', 0);' +
'}' +
'to {'
'transform: translate(' + to + ', 0);' +
'}' +
'}';
// Add it to the page
document.head.appendChild(style);
function transitionEnd(event) {
// Beware of bubbled events
if (event.target != elm) { return; }
// Clear the animation
elm.style.animation = '';
// Clean up the DOM
document.head.removeChild(style);
// Retain the final position
elm.style.transform = 'translate(' + to + ', 0)';
// We don't want that listener firing for future anims
elm.removeEventListener('animationend', transitionEnd);
done();
}
// Listen for end of transition
elm.addEventListener('animationend', transitionEnd);
// Start the animation
elm.style.animation = animName + ' 3s linear forwards';
}
Ugh! All of that just to move a thing? It works, but all of that DOM work is heavy-handed for what we’re trying to achieve. Also, if an animation is cancelled halfway through (for example, if the animation style is changed), then animationend will not fire — meaning that our done callback won’t fire or, worse, it’ll fire at the end of some future unrelated animation. There is no animationcancel event.
It’s early days for the Web Animations specification, but it’s pretty exciting. It brings a boatload of animation performance and synchronization features natively to the DOM that JavaScript libraries currently have to hack their way through.
The specification itself is kinda terrifying. My heart sank as I opened the page and watched the scrollbar get smaller and smaller. But, thankfully, most of it is implementation detail.
Here’s how we’d script our animation in the brave new world of Web Animation:
// Set our start position
elm.style.transform = 'translate(250px, 0)';
// Animate to the end position
var anim = elm.animate({
transform: 'translate(500px, 0)'
}, 3);
// Do something on completion
anim.onend = function() {
console.log('Done!');
};
Here, elm is an HTMLElement. The API is intuitive, especially if you’ve created animations with something like jQuery.
Like CSS animations and transitions, it gives the browser the full story up front, so we get all of the same optimizations without having to dynamically build CSS. Web Animations solves this by allowing us to tell the browser the full story of what we’re going to do. Then, the browser can go off and animate things itself.
Web Animations give us the scripting API to browser-driven animation that’s sorely missing. Above is the “Hello world” example. The specification includes advanced easing, path-based animation, parallelization, synchronization, interrupting and adapting, all in a way that the browser can take away from JavaScript land and optimize accordingly.
It’s still very early days, so don’t throw out your animation libraries yet. But if you want to experiment with the new API and provide feedback, a polyfill is tracking the rapidly evolving spec. Exciting times!
(al)
© Jake Archibald for Smashing Magazine, 2013.
Before 1998, the birth year of CSS Level 2, form elements were already widely implemented in all major browsers. The CSS 2 specification did not address the problem of how form elements should be presented to users. Because these elements are part of the UI of every Web document, the specification’s authors preferred to leave the visual layout of such elements to the default style sheet of Web browsers.
Through the years, this lack of detail in the CSS specification has forced Web developers to produce a significant number of tests and examples whose primary goal is to reduce form elements to a common visual denominator in order to get a cross-browser rendering of elements such as input, select, fieldset, legend and textarea. In this article, we will cover some of the CSS patterns used by Web developers to tame the visual layout of form elements.
Back in 2004 and later in 2007, Roger Johansson created a complete test suite for form elements and CSS. These seminal tests, which can be found in his article “Styling Form Controls With CSS, Revisited,” lead to the frustrating conclusion that Johansson summarizes with the following words:
“So what does this experiment show? Like I already stated, it shows that using CSS to style form controls to look exactly the same across browsers and platforms is impossible. It also shows that most browsers ignore many CSS properties when they are applied to form controls.”
Despite the underlying truth of these conclusions, Web developers continued to extensively test CSS styles on form elements to find the Holy Grail of — or at least a reasonable compromise between — the browser’s default rendering and the author’s styles.
The CSS 2.1 specification states in its proposed default style sheet for HTML4 that form elements such as textarea, input and select are inline-block elements:
textarea, input, select {
display: inline-block;
}
Conversely, the form and fieldset elements are block-level elements:
fieldset, form {
display: block;
}
The default model proposed by the CSS specification stops here. All other visual aspects of form elements rely on the browser’s default style sheet. However, the above rules indicate the following:
line-height and vertical-align to control the height of the box and its vertical alignment. Padding and margins can also be applied to define the outer and inner spacing of the affected box. As well, inline-block elements accept widths and heights because they share the block formatting model.fieldset and legend elements because legend relies entirely on the default styles provided by Web browsers.How do Web developers manage these problems?
Web developers soon noticed that Web browsers handle inline-block elements oddly when it comes to defining dimensions. Defining an height often leads to unexpected results:
input, select {
width: 120px;
height: 32px;
}
Developers tried to fix this problem by turning these elements into block-level elements:
input, select {
width: 120px;
height: 32px;
display: block;
}
Results are still poor, except for the textarea element. A common pattern to solve this problem is to avoid the height property and instead to use the font-size and padding properties.
Browsers do not use the same font family and size on these elements, so the first thing to do is normalize them:
input, select {
width: 120px;
font: 1em Arial, sans-serif;
}
For an example, see the page “CSS: Defining Form Element Dimensions” on jsFiddle.
Once the font in use is normalized, you can add padding to give some inner spacing to the element’s box:
input, select {
width: 120px;
font: 1em Arial, sans-serif;
padding: 3px 6px;
}
The input elements and textarea also show a border that affects their box model:
input[type="text"],
input[type="password"],
textarea {
border: 1px solid #ccc;
}
The input elements of the types button and submit have additional padding set by Web browsers. So, a common practice is to normalize them:
input[type="button"],
input[type="submit"] {
padding: 2px;
}
The problem with this approach is that Web browsers also apply vendor-specific properties to these elements, so our padding is not always able to normalize this property. For example, in a Webkit-based browser, you might have this:
input[type="button"], input[type="submit"],
input[type="reset"], input[type="file"]::-webkit-file-upload-button,
button {
-webkit-box-align: center;
text-align: center;
cursor: default;
color: buttontext;
padding: 2px 6px 3px;
border: 2px outset buttonface;
border-image: initial;
background-color: buttonface;
box-sizing: border-box;
}
input[type="button"], input[type="submit"], input[type="reset"] {
-webkit-appearance: push-button;
white-space: pre;
}
Padding is also used on the fieldset and legend elements but with different results:
fieldset to 0 will reset the default indentation of the legend elements in some browsers (though not in IE).legend to 0 has the effect of making this element shrink.Select boxes, checkboxes and radio buttons can be normalized with good results with only a few properties, namely:
font-family,font-size,width (on select boxes),padding.Applying other properties to this group of elements often leads to inconsistent results across browsers.
Form elements can be vertically or horizontally aligned. They can be laid out on the same line or as a group of boxes on multiple rows. To align them on the same line, you can follow one of two approaches:
When you use floating, elements are automatically turned into block-level elements. This means that form elements are now subject to the nine rules that govern floated elements.

Form elements can be vertically or horizontally aligned.
With floats, the main challenge is to achieve good vertical alignment on the current line. In this case, using vertical margins or padding is a common practice:
input, select {
width: 120px;
float: left;
margin-top: 0.4em;
}
This approach works when you do not have to align boxes with text, such as with the contents of a label element. In this case, you could use relative positioning, padding or margins on the element that contains only text:
label {
float: left;
padding-top: 0.4em;
width: 5em;
margin-right: 1em;
}
Another problem arises with buttons. In this case, when you have a button whose dimensions are greater than those of other elements, you can force its vertical alignment with relative positioning:
input[type="submit"] {
float: left;
width: 90px;
position: relative;
top: 0.4em;
}
This approach with relative positioning also works with checkboxes and radio buttons. Relative positioning can even be applied to normalize the left indentation of the legend element within a fieldset element, the only difference being that you would use the left property instead of top.
When using inline formatting, you can rely on the vertical-align property to vertically align elements:
label, input[type="text"] {
vertical-align: middle;
margin-right: 1em;
}
Good results can be achieved by combining this property with the line-height property. However, this property must be set on the parent element. If you set this property directly on the form’s elements, their computed height would be affected:
.form-row {
line-height: 1.4;
}
Using a declared height on the parent element is also effective when paired with the same value for the line height:
.form-row {
line-height: 1.8;
height: 1.8em;
}
With inline formatting, you can also use the text-align property on the parent element to align elements to the right, left or center.
The file input element — that is, <input type="file"/> — is a special case. This kind of element must always be visible and recognizable in the browser’s UI for security reasons. This implies that browsers deliberately ignore some style rules (such as those related to visibility) and tend to apply the algorithms defined in their default style sheet.
Furthermore, the default rendering varies from browser to browser: some browsers display only a single button, while others add a text field to display the path of the uploaded file.
Web developers, however, soon found a way to circumvent these limitations. First, they wrapped the input element in a container:
<form action="" method="post" enctype="multipart/form-data">
<div class="upload">
<input type="file" name="upload"/>
</div>
</form>
Then, they hid the input element using the opacity property and applied certain styles to the input’s container:
.upload {
width: 157px;
height: 57px;
background: url(upload.png) no-repeat;
overflow: hidden;
}
.upload input {
display: block !important;
width: 157px !important;
height: 57px !important;
opacity: 0 !important;
overflow: hidden !important;
}
Notice the !important statement. This is the preferred way to override the browser’s default rules.
For an example, see the page “CSS: Styling Inputs of Type ‘file’” on jsFiddle.
Totally taming form elements is impossible due to the lack of detail in the CSS specification and because of the default styles applied by Web browsers. However, by following some common practices, reducing (though not eliminating) the differences and achieving good visual results are possible.
(al)
© Gabriele Romanato for Smashing Magazine, 2013.
Being a premium HTML5 template, Moksh is a simple and easy to use corporate flavoured theme with responsive layout built using Twitter Bootstrap. theme …
themeforest.net/item/moksh-responsive-html5…/4268780

Mac OS X includes a few system-level menu bar items that are incredibly useful, but if you’ve ever wanted to have a few extras to your menu bar consider these four essentials. All free, they’ll bring a wide variety of function to the menu bar, where you’ll be able to quickly see the weather, make using your computer at night much easier on the eyes, control sleep and screen saver behavior, and even toggle some really useful system functions.
Check out each below, and don’t forget to let us know in the comments if we’re missing a menu bar essential.

Maybe it’s because so many of us work in doors these days, but there’s something about knowing the weather and temperature that is just greatly appreciated. You’ll know whether you need to put on a coat or take off that sweater before going outside, and one of the easiest ways to determine what the temperature is outside is to use a simple menu bar utility like Degrees. With Degrees, you’ll always know the current temperature (in celcius or fahrenheit), and the current weather conditions as indicated by a little icon that sits in your menu bar. Set it to discover your location and it’ll update itself if you’re on the go between locations. Simple, unobtrusive, free, and no hassle.
There are definitely other menubar items and apps out there to show you the weather, but Degrees is fairly new, is fairly lightweight, and arguably has the best icons, and thus has won me over.

In early mornings and late evenings, the incredibly bright white light emitted from computer screens can be harsh on the eyes, cause eye strain, and this so-called “blue light” can even be disruptive to sleep patterns and melatonin production – yes, seriously, there is a lot of research on this stuff. This is where Flux comes in, it will automatically adjust the color hue of your screens display based on the lighting conditions and the time of day. It can be a little strange at first, but once you get accustomed to using it, you’ll find the sepia tones it casts on the display at night is just so much easier to look at. You’ll have less eye strain, and maybe even sleep better too.
Flux is best used when adjusting the brightness with it as well, so lower your screens brightness a bit at night and in early mornings and you’ll get the most benefit. Flux is available for other platforms as well, so if you have a PC you’ll also be able to run it too, and if you jailbreak iPhone or iPad, you can even get F.lux on those devices too through Cydia.

Having your Mac screen automatically lock itself and require a password to use again is a simple common sense security trick, whether you’re at home, in an office, at school, or anywhere else. But oftentimes we’re still sitting at a desk and just not using the computer, whether it’s because we’re performing another task, or even just reading hands-free, and in these situations it’s kind of a pain for the screen saver to activate itself or the computer to put itself to sleep, and then have to enter a password again just to use it again. This is where both Caffeine and Wimoweh come into play.
Caffeine is very straight forward, click the coffee-cup icon and the Mac screen temporarily won’t go to sleep or activate a screen saver, click it again and things will sleep again as usual.
Wimoweh is similar but just slightly more advanced, letting you control sleep prevention on a per-app basis, in addition to having the standard no-sleep feature.
They’re both great apps, and they’re both free, so use whichever works best for your work flow. The screenshot shown is of Caffeine.

DesktopUtility lets you toggle 3 incredibly useful features right in your menubar, without having to use the defaults writes commands and manually relaunching the Finder: hide desktop icons and show them again, show invisible files and hide them again, and show the user library or hide it again. No more launching Terminal to toggle those settings on and off again, just pull down the gear menu, select which you want, and the proper command will be executed, and the Finder will restart itself.
DesktopUtility is particularly useful for advanced users who frequently need to access the user library and see files that are otherwise invisible, and being able to quickly make desktop icons disappear (they still exist, they’re just not visible on the desktop) is a simple way to instantly clean up a desktop without having to do any work… we recommend other approaches for that of course but when all else fails just hiding the clutter can often be enough to relieve the stress of a busy desktop filled with icons of files and folders.
Did we miss an essential menu bar item that you get a lot of use out of? Let us know in the comments!
And don’t forget, you can easily remove system menu bar items by command+dragging them out of the menubar, but for third party apps like those mentioned above you’ll need to individually quit out of the app itself.
Walt Disney Co.’s troubled interactive division will have a tougher time reaching profitability this year, a goal Chief Executive Robert Iger had touted to shareholders.
The media conglomerate said Wednesday that its heavily hyped videogame, Disney Infinity, won’t be released in June as planned. It will instead come out on Aug. 18, meaning less revenue from the game — the biggest release from its interactive division — will be counted in Disney’s fiscal year, which ends in September.
Google just announced the launch of its Google Drive Realtime API, a new tool for developers that will allow them to bring the same real-time collaboration features that power Google Drive to their own apps. The API, Google writes, “handles network communication, storage, presence, conflict resolution, and other collaborative details so you can focus on building great apps.” Google partnered with three-developer focused tools, the collaborative code editor Neutron Drive, the project scheduling tool Gantter and the diagraming tool draw.io to test and launch this API.
To show off the power of the API, Google also developed a cube puzzle that uses the Realtime API, as well as a Drive Realtime API Playground for testing the API. Developers, of course, also need to sign up for the Drive API before they can use the Realtime API, too.
The API, Google writes, provides “collaborative versions of familiar data objects such as maps, lists, strings, and JSON values and automatically synchronizes and stores modifications to these objects.” In addition, developers can also add custom objects and references.
Because the API tracks the collaborators’ presence, developers can alert users when others join, leave or make changes to a document.
Just like on Drive, the Realtime API also ensures that local changes are immediately reflected in the local document thanks to Google’s use of operational transformation (OT) at the core of the system. This means your local app will continue to feel responsive, even on high-latency networks.