HTML5 Boilerplate Framework Tutorial
In this article, we’ll be going through a very popular HTML5 framework, maybe the most popular one, HTML5 Boilerplate.
HTML5 Boilerplate helps you build fast, robust, and adaptable web apps or sites. This project is the product of many years of iterative development and combined community knowledge. It does not impose a specific development philosophy or framework, so you’re free to architect your code in the way that you want.
You can find the source code in the official github repository: https://github.com/h5bp/html5-boilerplate
1. Main Features
You might be wondering, why use Boilerplate, what’s on it? Well, below we present the best features:
– HTML5 ready. Use the new elements with confidence.
– Designed with progressive enhancement in mind.
Includes:
– Normalize.css
for CSS normalizations and common bug fixes
– jQuery
via CDN, with a local fallback
– A custom build of Modernizr
for feature detection
– Apache Server Configs
that, among other, improve the web site’s performance and security
– Placeholder CSS Media Queries.
– Useful CSS helper classes.
– Default print styles, performance optimized.
– An optimized version of the Google Universal Analytics snippet.
– Protection against any stray console statements causing JavaScript errors in older browsers.
– “Delete-key friendly.” Easy to strip out parts you don’t need.
– Extensive inline and accompanying documentation.
2. Browser Support
Browser support is a very important aspect to consider when developing web projects. Boilerplate offers a wide range of browser support and even support for their earlier versions.
– Chrome (latest 2)
– Firefox (latest 2)
– Internet Explorer 8+
– Opera (latest 2)
– Safari (latest 2)
This doesn’t mean that HTML5 Boilerplate cannot be used in older browsers, just that they’ll ensure compatibility with the ones mentioned above.
3. The HTML of Boilerplate
By default, HTML5 Boilerplate provides two html
pages:
1. index.html
– a default HTML skeleton that should form the basis of all pages on your website.
2. 404.html
– a placeholder 404 error page.
3.1 Inside index.html
The no-js
class
The no-js
class is provided in order to allow you to more easily and explicitly add custom styles based on whether JavaScript is disabled (.no-js) or enabled (.js). Using this technique also helps avoid the FOUC.
Language attribute
Do consider specifying the language of your content by adding the lang attribute to as in this example:
<html class=”no-js” lang=”en”>
The order of the <title> and <meta> tags
The order in which the <title> and the <meta> tags are specified is important because:
1) the charset declaration (<meta charset=”utf-8″>):
– must be included completely within the first 1024 bytes of the document
– should be specified as early as possible (before any content that could be controlled by an attacker, such as a <title> element) in order to avoid a potential encoding-related security issue in Internet Explorer
2) the meta tag for compatibility mode (<meta http-equiv=”x-ua-compatible” content=”ie=edge”>):
– needs to be included before all other tags except for the <title> and the other <meta> tags
x-ua-compatible
Internet Explorer 8/9/10 support document compatibility modes that affect the way webpages are interpreted and displayed. Because of this, even if your site’s visitor is using, let’s say, Internet Explorer 9, it’s possible that IE will not use the latest rendering engine, and instead, decide to render your page using the Internet Explorer 5.5 rendering engine.
Specifying the x-ua-compatible
meta tag:
or sending the page with the following HTTP response header
X-UA-Compatible: IE=edge
will force Internet Explorer 8/9/10 to render the webpage in the highest available mode in the various cases when it may not, and therefore, ensure that anyone browsing your site is treated to the best possible user experience that browser can offer.
If possible, we recommend that you remove the meta
tag and send only the HTTP response header as the meta
tag will not always work if your site is served on a non-standard port, as Internet Explorer’s preference option Display intranet sites in Compatibility View is checked by default.
If you are using Apache as your webserver, including the .htaccess file takes care of the HTTP header. If you are using a different server, check out our other server config.
Mobile viewport
There are a few different options that you can use with the viewport
meta tag. You can find out more in the Apple developer docs. HTML5 Boilerplate comes with a simple setup that strikes a good balance for general use cases.
<meta name="viewport" content="width=device-width, initial-scale=1">
Modernizr
HTML5 Boilerplate uses a custom build of Modernizr.
Modernizr is a JavaScript library which adds classes to the html
element based on the results of feature test and which ensures that all browsers can make use of HTML5 elements (as it includes the HTML5 Shiv). This allows you to target parts of your CSS and JavaScript based on the features supported by a browser.
In general, in order to keep page load times to a minimum, it’s best to call any JavaScript at the end of the page because if a script is slow to load from an external server it may cause the whole page to hang. That said, the Modernizr script needs to run before the browser begins rendering the page, so that browsers lacking support for some of the new HTML5 elements are able to handle them properly. Therefore the Modernizr script is the only JavaScript file synchronously loaded at the top of the document.
What about polyfills?
A polyfill, or polyfiller, is a piece of code (or plugin) that provides the technology that you, the developer, expect the browser to provide natively. Flattening the API landscape if you will. If you need to include polyfills in your project, you must make sure those load before any other JavaScript. If you’re using some polyfill CDN service.
window.jQuery || document.write('')
The content area
The central part of the boilerplate template is pretty much empty. This is intentional, in order to make the boilerplate suitable for both web page and web app development.
Google CDN for jQuery
The Google CDN version of the jQuery JavaScript library is referenced towards the bottom of the page using a protocol-independent path (read more about this in the FAQ). A local fallback of jQuery is included for rare instances when the CDN version might not be available, and to facilitate offline development.
The Google CDN version is chosen over other potential candidates (like the jQuery CDN) because it’s fast in absolute terms and it has the best overall penetration which increases the odds of having a copy of the library in your user’s browser cache.
While the Google CDN is a strong default solution your site or application may require a different configuration. Testing your site with services like WebPageTest and browser tools like PageSpeed Insights or YSlow will help you examine the real world performance of your site and can show where you can optimize your specific site or application.
Google Universal Analytics Tracking Code
Finally, an optimized version of the Google Universal Analytics tracking code is included. Google recommends that this script be placed at the top of the page. Factors to consider: if you place this script at the top of the page, you’ll be able to count users who don’t fully load the page, and you’ll incur the max number of simultaneous connections of the browser.
Finally, this is how the HTML of Boilerplate looks like in your editor:
4. The CSS of Boilerplate
HTML5 Boilerplate’s CSS includes:
• Normalize.css
• Useful defaults
• Common helpers
• Placeholder media queries
• Print styles
This starting CSS does not rely on the presence of conditional class names, conditional style sheets, or Modernizr, and it is ready to use no matter what your development preferences happen to be.
4.1 Normalize.css
In order to make browsers render all elements more consistently and in line with modern standards, we include Normalize.css — a modern, HTML5-ready alternative to CSS resets.
As opposed to CSS resets, Normalize.css:
• targets only the styles that need normalizing
• preserves useful browser defaults rather than erasing them
• corrects bugs and common browser inconsistencies
• improves usability with subtle improvements
• doesn’t clutter the debugging tools
• has better documentation
4.2 Useful defaults
Several base styles are included that build upon Normalize.css. These styles:
• provide basic typography settings that improve text readability
• protect against unwanted text-shadow during text highlighting
• tweak the default alignment of some elements (e.g.: img, video, fieldset, textarea)
• style the prompt that is displayed to users using an outdated browser
You are free and even encouraged to modify or add to these base styles as your project requires.
4.3 Common Helpers
Along with the base styles, we also provide some commonly used helper classes.
.hidden
The hidden
class can be added to any element that you want to hide visually and from screen readers. It could be an element that will be populated and displayed later, or an element you will hide with JavaScript.
.visuallyhidden
The visuallyhidden
class can be added to any element that you want to hide visually, while still have its content accessible to screen readers.
.invisible
The invisible
class can be added to any element that you want to hide visually and from screen readers, but without affecting the layout.
As opposed to the hidden class that effectively removes the element from the layout, the invisible class will simply make the element invisible while keeping it in the flow and not affecting the positioning of the surrounding content.
.clearfix
The clearfix
class can be added to any element to ensure that it always fully contains its floated children.
Over the years there have been many variants of the clearfix hack, but currently, we use the micro clearfix.
4.4 Media Queries
HTML5 Boilerplate makes it easy for you to get started with a mobile first and responsive web design approach to development. But it’s worth remembering that there are no silver bullets.
We include placeholder media queries to help you build up your mobile styles for wider viewports and high-resolution displays. It’s recommended that you adapt these media queries based on the content of your site rather than mirroring the fixed dimensions of specific devices.
If you do not want to take the mobile first approach, you can simply edit or remove these placeholder media queries. One possibility would be to work from wide viewports down, and use max-width
media queries instead (e.g.: @media only screen and (max-width: 480px)
).
4.5 Print styles
Lastly, we provide some useful print styles that will optimize the printing process, as well as make the printed pages easier to read.
At printing time, these styles will:
• strip all background colors, change the font color to black, and remove the text-shadow — done in order to help save printer ink and speed up the printing process
• underline and expand links to include the URL — done in order to allow users to know where to refer to
(exceptions to this are: the links that are fragment identifiers, or use the javascript: pseudo protocol)
• expand abbreviations to include the full description — done in order to allow users to know what the abbreviations stands for
• provide instructions on how browsers should break the content into pages and on orphans/widows, namely, we instruct supporting browsers that they should:
₀ ensure the table header (
) is printed on each page spanned by the table ₀ prevent block quotations, preformatted text, images and table rows from being split onto two different pages ₀ ensure that headings never appear on a different page than the text they are associated with ₀ ensure that orphans and widows do not appear on printed pages.
5. The Javascript of Boilerplate
5.1 main.js
This file can be used to contain or reference your site/app JavaScript code. For larger projects, you can make use of a JavaScript module loader, like Require.js, to load any other scripts you need to run.
5.2 plugins.js
This file can be used to contain all your plugins, such as jQuery plugins and other 3rd party scripts.
One approach is to put jQuery plugins inside of a (function($){ ... })(jQuery);
closure to make sure they’re in the jQuery namespace safety blanket. Read more about jQuery plugin authoring.
By default the plugins.js file contains a small script to avoid console errors in browsers that lack a console
. The script will make sure that, if a console method isn’t available, that method will have the value of empty function, thus, preventing the browser from throwing an error.
6. Using the Framework
The folder structure of Boilerplate is this:
├── css
│ ├── main.css
│ └── normalize.css
├── doc
├── img
├── js
│ ├── main.js
│ ├── plugins.js
│ └── vendor
│ ├── jquery.min.js
│ └── modernizr.min.js
├── .htaccess
├── 404.html
├── index.html
├── humans.txt
├── robots.txt
├── crossdomain.xml
├── favicon.ico
└── [apple-touch-icons]
6.1 Popular boilerplates
HTML5 Boilerplate is a good place to start. The self-described “web’s most popular front-end template” is sleek, simple and the result of the pooled knowledge of many dozens of developers. It provides the basic scaffolding or framework for building an entire website.
There are alternative methods, which happen to provide more assistance. Bootstrap, Web Starter Kit and Skeleton add things like a typography base and responsive grid, giving you a further head-start when working on your design. However, they do so at the expense of additional default code, which you may find yourself having to edit or override.
There are also arguments that rather too many designers in recent years have relied heavily on Bootstrap, thereby resulting in many sites looking alike. Using a simpler foundation and going your own way could therefore be a better choice, depending on your level of ability, confidence and needs.
6.2 Advanced boilerplates
Based on HTLM5 Boilerplate, Initializr generates a clean customizable template for you
Once you gain experience, it’s worth considering a custom build using Initializr, retaining the components you need and ditching those you don’t. Also, if you’re creating a WordPress site, explore a WordPress-specific blank theme, such as HTML5 Blank.
These downloads and services are all free, and so you can check out and experiment with them at your leisure. For now, though, we’re going to concentrate on HTML5 Boilerplate.
6.3 Usage of the HTML5 Boilerplate
This free, open-source boilerplate when downloaded provides you with documentation and licensing in Markdown format, some CSS, two placeholder images, two HTML files, some JavaScript, and some server config files.
On downloading the archive, make a copy and keep it clean and untouched. It can then serve as reference for any changes you make. For the new site you’re working on, you can ditch all of the .md documents. You’ll also want to replace the two .png files with your own, otherwise the HTML5 Boilerplate logo will appear as your site’s favicon and also the icon when your site is saved to someone’s iOS Home screen. An online generator can help you create new images.
Regarding the HTML, there might be some things in there that you’re not familiar with. The majority of these additions deal with issues relating to legacy browsers; the final script element is for Google Analytics and can be removed entirely if you don’t use that. Leave the other script elements that are found towards the end of the file, because they load jQuery.
Otherwise, beyond adding content to the body of the document, after the ‘Add your site or application content here’ comment, you’ll need to give the page a title and fill the ‘content’ value in the ‘description’ meta tag.
Pretty straight forward, you download the framework files, which you can consider as a template, and then edit the necessary files to get you project going.
So I went ahead and added some lines into the main index.html and then edited the main.css inside css folder to customize my little page. The result was really great, considering that I didn’t have to write lines of code about linking assets, or any other type of declaration. I just added my code like so:
– HTML
The HTML contains a heading div, a subheading, a paragraph and an image. It is all wrapped in one wrapper
div, inside of which we have the main heading1
div and a content
div. Note the actual code is put under the body section, and the template default code remains unchanged. Isn’t that awesome?
– CSS
Adding your own CSS will give the page styling, so in the framework CSS file I’ve added styles to enlarge the heading div, make it bold and give it a gray color. The wrapper got a centered look and a round padding. I also changed the paragraph text style to italic and gave it a green color. As you can notice, the image only has a soft shadow added.
This is how my page looked like in the browser:
Simple as that, nothing changed, just added my own content and enjoyed fast and reliable coding.
7. Conclusion
To conclude, HTML5 Boilerplate is a very basic but powerful HTML framework that enables distraction free coding, you already have all your assets linked (css and js) and all you do is start coding the body (the main part) of your web project. You can keep on adding the various snippets in css and js files provided and never have to worry about linking, mobile scaling, browser support and so on.
In a nutshell, Boilerplate is a lean, mobile-friendly HTML template with optimized Google Analytics snippet, placeholder touch-device icon; and docs covering dozens of extra tips and tricks. Feel free to visit the official site: https://html5boilerplate.com/
8. Download
You can download the full source code of this example and the Boileplate framework files here:
HTML5 Boilerplate Framework
Thanks for your article, thanks for your book. I love it :D
Nice article keep it up. Though I need to learn html5 boiler plate.
I think it is sleek and sharp and clear.
Will u participate in my blog
Blog.ncon.in
Why did you use a for your main heading rather than a and tags combination? Seems like the latter would be more accessible to screen readers