How to create an awesome blog template using Bootstrap 3 - Part I
Table of Contents
- 1. Preface
- 2. Part I � Create basic blog template with Bootstrap 3
- 3. What tools we need?
- 4. Twitter Bootstrap? What's that?
- 5. Creating a blog template
- 6. Create the home page
- 6.1 Pick up the right editor
- 6.2 Download Bootstrap and jQuery libraries
- 6.3 Create the basic structure
- 6.4 Create page header that wraps logo, navigation and search textbox
- 6.5 Create single and two-column layouts for main content and sidebar
- 6.6 Create the HTML markup for latest posts section
- 6.7 Create sidebar widgets
- 7. Create the single post page
- 8. Create the contact page
- 9. Create the about me page
- 10. Summary
1. Preface
Are you one who doesn't have great design skills but looking for stuff to create nice templates in a short time? Are you one who recently heard about this nice framework called Twitter Bootstrap and don't have much knowledge or experience to customize and create some website that represents your brand? Well folks, this tutorial is for you.
Actually, this is not just a tutorial but workshop. At the end of this workshop, you'll gain two things: First, you'll have a beautiful blog template that you could use right away for your website. Second, which is the most important thing, you'll know how to create stunning templates by yourself which jaw-drops others. Here after, you won't be googling to search for any free template, because you know how to create one with the help of Bootstrap. At the time of writing this, the latest version of Twitter Bootstrap is 3, we'll be using the same in this workshop.
Due to time constraint and content size, I've divided this workshop into two parts. In the first part, which is going to be very simple, we are going to create a complete blog template using Bootstrap. At the end of this first part, you'll have a nice blog template with home, single-post, contact and about-me pages.
In the second part, which is going to be more interesting one, where we'll see, how we can download the Bootstrap source code and customize it to create our own theme that matches our imagination.
2. Part I � Create basic blog template with Bootstrap 3
As I already said, in this part, we'll create the basic blog template using Bootstrap 3 that includes all the pages required for a typical blog like home, single-post, contact and about me pages. At the end of this part, you'll have a complete blog template that you can use right away.
The below images show how our blog template appears in mobile and desktop screens after completing this part.
After completing this part, I recommend you to go through part 2 that will teach you how you can customize and create your own custom theme.
3. What tools we need?
- Text editor
- Google Chrome Browser
You need a text editor for composing html, css and js files. At the moment, my favourite one is Sublime Text 2. You could use any one of your choices. You would also need a mobile emulator. A mobile emulator helps you to see how the page appears in a preferred mobile device. We can use Google's Chrome browser for emulation which emulates the output to more than dozen devices from Amazon Kindle to Sony Xperia.
4. Twitter Bootstrap? What's that?
Twitter Bootstrap is a front-end framework developed by couple of good hearted guys from Twitter - Mark Otto and Jacob Thornton. The framework helps you to easily create website layouts through mobile first approach using its powerful grid system and lot of widgets. The framework provides a lot of CSS classes through which you can convert a plain looking unordered list into an amazing navigation component. Bootstrap helps developers who have a very little design knowledge to quickly wrap up a decent looking website.
The framework is MIT licensed and have a strong development community of over 400 contributors in GitHub. Thousands of websites uses Bootstrap for front-end decoration and some of the quick ones I found in net are: Webflow, Sentry, Engine Yard etc. Many websites that uses Bootstrap don't customize much, which make users eyes weary with the same look and feel. We are not going to do the same mistake, promise!.
Bootstrap is built on the foundation of LESS. Through LESS we can easily customize the framework according to our brand. There are many tools available like JetStrap, LauoutIt etc. helps us to dynamically craft website templates online using Bootstrap.
5. Creating a blog template
There are lot of bootstrap blog templates available online for free and paid; but, it's usually hard to find something that exactly meets your dream. Luckily with Bootstrap, creating a perfect template is not a hard job and you are going to see it how. One important thing I've to take into account is, I want the blog template should give best user experience for non-desktop (mobile, tablets) users as well. With Bootstrap 3's new mobile first approach this is terribly easy now. Starting things from the small screen helps us to focus on primary content first. We'll try to apply the same approach throughout in this workshop.
In this first part of the workshop, the following are the tasks we are going to do.
1. Create the home page
2. Create the single post page
3. Create the contact page
4. Create the about me page
Yeah, that's very high-level breakdown. We'll break each into further sub-tasks on the way.
6. Create the home page
In creating the home page, we will be doing most of the plumbing work required for other pages as well. Before getting into code, you should mentally visualize about the layout, the primary elements, their placement in the page from small to big screen. You could use a rough paper or some online tool like Balasamiq to draw the mockups that resides in your mind. I've used Balasamiq.
What you see below are the mockups that I've come up for the home page, both mobile and desktop.
Do you like the design? Pretty simple and straight, isn't it? Pardon me, I haven't kicked my imagination horse too hard, I guess!
In mobile devices, we want the site to flow as a single column. In tablets, desktops we want the content stream to divide and flow into two columns. The layout is composed of header and footer which is shared across pages. If you scan the design, the important elements are header (which contains logo, navigation and search textbox), main body content (displays the latest blog posts), sidebar and footer. Not only for the main elements, we should think about the structure and arrangement for each small element like the repeating post section, sidebar widget and others. The design pretty much tells the story about most of them.
I hope we are clear with the design, it's time to make the playground ready!
- Pick up the right editor
- Download Bootstrap and jQuery libraries
6.1 Pick up the right editor
There are lot of text editors available for editing html, css and js files. Couple of the tools I frequently use are Notepad++ and SublimeText 2. Now-a-days, I spent most of the time with SublimeText 2. You can use any one of them or some other.
6.2 Download Bootstrap and jQuery libraries
You can download Bootstrap library from their website.
The Bootstrap website itself designed using Bootstrap 3, you could already feel what we are up-to, don't you? You could see two big buttons "Download Bootstrap" and "Download Source". Please click the first one. The later one will download the complete source code which we'll be doing anyway in Part 2.
Bootstrap has dependency with jQuery. You can download the latest version of jQuery from their website. You could also refer from CDN if you wish.
Create a new folder called MyBlogTemplate somewhere in your hard drive that should include both the downloaded libraries.
If you are using SublimeText 2, you can open the folder MyBlogTemplate using the "Open Folder" option from the "File" menu.
If you see the home page mockup (Fig 3 & 4), its body content is divided into two: main or primary content which contains the list of latest posts and sidebar which contains stack of widgets. In mobile, both the main content and sidebar occupies 100% of the screen. Since, we've more room in desktop, the primary content takes 2/3rd (67%) and the sidebar takes 1/3rd (33%) of the entire screen.
I've broken down the complete home page creation tasks into the following subtasks.
a. Create the basic structure
b. Create page header that wraps logo, navigation and search textbox
c. Create single and two-column layouts for main content and sidebar
d. Create the HTML markup for latest posts section
e. Create sidebar widgets
For each task, we are going to leverage Bootstrap to create the markup.
6.3 Create the basic structure
Here we go with our first task - preparing the basic HTML.
Create a new file with name index.html under the folder MyBlogTemplate. Fill the file with the below stuff.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="A Bootstrap Blog Template"> <meta name="author" content="Vijaya Anand"> <title>Home</title> </head> <body> </body> </html>
Listing 1. Base markup in index.html
You already know about most of the pieces which I filled above, though, I would like to explain about couple of them: DOCTYPE and Viewport meta tag.
6.3.1 HTML5 DOCTYPE
<!DOCTYPE html>
Listing 2. DOCTYPE tag
We are going to build our pages in HTML5. The above line tells the browsers, "Hey, this page is written in HTML5, please use the same to validate".
More about DOCTYPE
The <!DOCTYPE> declaration must be the very first thing in your HTML document, before the <html> tag.
The <!DOCTYPE> declaration is not an HTML tag; it is an instruction to the web browser about what version of HTML the page is written in.
In HTML 4.01, the <!DOCTYPE> declaration refers to a DTD, because HTML 4.01 was based on SGML. The DTD specifies the rules for the markup language, so that the browsers render the content correctly.
HTML5 is not based on SGML, and therefore does not require a reference to a DTD.
Tip: Always add the <!DOCTYPE> declaration to your HTML documents, so that the browser knows what type of document to expect.
6.3.2 Viewport meta tag
<meta name="viewport" content="width=device-width, initial-scale=1.0">
Listing 3. Viewport meta tag
<meta> tags are uses to convey metadata information (description, keywords, author) about HTML documents. The above meta-tag gains more importance in regard with mobile browsers. It tells the browser to take device width as the virtual viewport width (see the below help section) and set the zoom level to default, this makes the browser not to completely zoom out the site and show it small.
A tale of two viewports: layout viewport and visual viewport
George Cummins explains the basic concept best here at Stack Overflow:
"Imagine the layout viewport as being a large image which does not change size or shape. Now image you have a smaller frame through which you look at the large image. The small frame is surrounded by opaque material which obscures your view of all but a portion of the large image. The portion of the large image that you can see through the frame is the visual viewport. You can back away from the large image while holding your frame (zoom out) to see the entire image at once, or you can move closer (zoom in) to see only a portion. You can also change the orientation of the frame, but the size and shape of the large image (layout viewport) never changes."
Before diving into further development let's reference the Bootstrap and jQuery libraries in our index file.
6.3.3 Reference jQuery and Bootstrap libraries
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="A Bootstrap Blog Template"> <meta name="author" content="Vijaya Anand"> <title>Home</title> <!-- Bootstrap CSS file --> <link href="bootstrap-3.0.3/css/bootstrap.min.css" rel="stylesheet" /> <link href="bootstrap-3.0.3/css/bootstrap-theme.min.css" rel="stylesheet" /> </head> <body> <!-- Jquery and Bootstrap Script files --> <script src="jquery-2.0.3.min.js"></script> <script src="bootstrap-3.0.3/js/bootstrap.min.js"></script> </body> </html>
Listing 4. Referencing Bootstrap and jQuery libraries
We've referenced two CSS files: bootstrap.min.css and bootstrap-theme.min.css. The bootstrap.min.css is the basic CSS file, which is mandatory. The second one, bootstrap-theme.min.css is optional which decorates the Bootstrap components with gradient and other arbitrary styles - a pleasing effect to the components!
6.3.4 Create the foundation
The layout can be segmented into three regions: header, body and footer. The header section contains the logo, navigation and search-box. The main content section varies from page to page. The footer section contains the typical copyright information.
To create these sections, let's throw some basic elements under <body>.
<body> <header> -- Logo, Navigation & Search Bar-- </header> <div id="body"> -- Site Main content -- </div> <footer> -- Copyright information -- </footer> </body>
Listing 5. Header, body and footer elements
We have used HTML5 elements for header and footer sections. The primary content of the body is represented by an empty div. If you open the file in browser, you could see the below screen - nothing interesting at the moment!
How about seeing the output in mobile mode? If you are using chrome, you could TURN ON the emulation mode by pressing F12. If you did, you could see a new container below the usual one which contains a menu called Emulation. If you don't see the Emulation tab make sure you have turned on the "Show 'Emulation' view in console drawer" from the Settings.
You can select any device from more than dozen options, I've selected the Apple iPhone 5. On clicking the Emulate button you could see the browser output transformed into iPhone screen. Cool, isn't it?
6.3.5 Bootstrap's container class
The page looks very normal in both desktop and mobile screens. Though the <header> and <footer> elements are not styled by Bootstrap, it overrides the default font-system and applies some predefined styles to the h1, h2..., anchor elements. Bootstrap mostly applies styles through CSS classes. If you notice the <header> and <footer> elements (Fig. 9 & Fig. 11), there is no much room for the placeholder texts resides inside them. It would be great if we set some padding for each of them to help their children get more room for breathe.
Before you think to create a CSS class and apply to each element, I would like to reveal you the first important class from Bootstrap called container. Containers are used to centre an element with padding at both left and right sides. It sets a fixed width to the element but the set width will be changed based on device's width.
Instead of directly applying the container CSS class to the <header> and <footer> elements, please create a child <div> element and apply to it. Applying the class directly on the <header> and <footer> element will not give the desirable design which we want here.
After you've done with the changes, the markup should look as below.
<body> <header> <div class="container"> -- Logo, Navigation & Search Bar �- </div> </header> <div id="body" class="container"> -- Site Main content -- </div> <footer> <div class="container"> -- Copyright information � </div> </footer> </body>
Listing 6. Applying "container" class
If you open the file in browser, it would look little better now. We've completed our first task. Let's work on the next one: header, which is going to be little tricky and interesting.
6.4 Create page header that wraps logo, navigation and search textbox
We are going to target an important piece in this task: navigation header. The header is composed of three pieces: logo, navigation and search-box. To implement this task we need to study what are Bootstrap components and what components they provide to support navigation. Let's spend some time on that.
6.4.1 Bootstrap components
Bootstrap provides a bunch of reusable components. We've components for icons, dropdowns, navigation, button groups, alerts, progress bars and more. These components are created through HTML markup decorated with special CSS classes from Bootstrap. Having a good knowledge of these CSS classes is like having a mighty sword in your hand, very helpful! It's not just the styles Bootstrap controls many things through CSS classes.
A simple Bootstrap component: Navigation
To create a navigation component you have to use following HTML markup with the shown CSS classes.
<ul class="nav nav-tabs"> <li class="active"> <a href="#">Home</a> </li> <li> <a href="#">Profile</a> </li> <li> <a href="#">Messages</a> </li> </ul>
Listing 7. Navigation markup fiddle it
This is how the navigation appears in Desktop Chrome.
6.4.2 Navbar component
For creating navigation headers, Bootstrap provides a nice component called Navbar. This component is more like an extended model of the navigation component (Nav). We are going to use this one for creating our navigation header.
6.4.3 A simple Navigation Bar
Let's start with simple! We can create a simple navigation bar with links to three pages with the below markup.
<nav class="navbar navbar-default"> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#">Contact</a></li> <li><a href="#">About</a></li> </ul> </nav>
Listing 8. Navigation bar markup fiddle it
If you view the above html fragment in the browser, you could see the below screens in mobile and desktop views.
In case of mobile, the navigation links are stacked one below another. While in desktop, since we have more room there, they sit horizontally next to each other. That's one of the best examples of "responsiveness". Internally, Bootstrap uses media queries to set breakpoints at different widths and adjust the styles of the NavBar component. Media Queries is a CSS3 feature that helps to render new styles based on screen resolution.
CSS 3 Media Queries
Media Queries is a CSS3 module allowing content rendering to adapt to conditions such as screen resolution. It became a W3C recommended standard in June 2012 and is a cornerstone technology of Responsive Web Design.
Media Queries can be applied to link element or it inline stylesheet.
<!-- CSS media query on a link element --> <link rel="stylesheet" media="(max-width: 800px)" href="example.css" /> <!-- CSS media query within a style sheet --> <style> @media (max-width: 600px) { .facet_sidebar { display: none; } } </style>
Listing 9. Media Queries
Let's explore the markup for the simple navigation bar and understand what are the important classes used to create it.
6.4.3.1 Exploring Markup
6.4.3.1.1 navbar and navbar-default
If you go through the markup shown in listing 8, we have a <nav> element that wraps an <ul> element. The <nav> element is decorated with two CSS classes navbar and navbar-default. It's these classes enhances the <nav> element to appear as a navigation bar. The former class gives the basic structure to the component while the later one gives the default style.
Instead of navbar-default you could also apply another CSS class called navbar-inverse. Well, what it does? It makes the navigation bar to stand-out like a dark knight, we'll be using the same in our case.
6.4.3.1.2 nav and navbar-nav
We need links to navigate to different pages and so we've an <ul> element. Note that, the <ul> element also decorated with couple of CSS classes: nav and navbar-nav. The nav class represents the <ul> element is used for navigation and navbar-nav tells bootstrap that the element appears inside a navigation bar and so decorate it accordingly.
Unless, we've an extra-ordinary memory system, It's difficult to remember all these classes, but, once you start using them frequently you will type them without knowing it.
6.4.4 Improving Navigation Bar for Mobile
The navigation bar appears to be OK in case of mobile views but not great! In mobile screen, they occupy most of the top space and user has to scroll down to see the main content which is definitely not a best user experience. A better approach is to collapse the navigation links and show them on clicking some button as shown below.
The above strategy is popular in small screens. To achieve that, we've to do changes to the markup and here where things going to get little complicated!
In our blog template, the header itself acts as navigation and so I've to apply the navigation bar classes directly to the <header> element itself. Also, taking the collapsible strategy into account, I've to make the following changes to the <header> element.
<body> <header class="navbar navbar-default bs-docs-nav" role="banner"> <div class="container"> <div class="navbar-header"> <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".bs-navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <nav class="collapse navbar-collapse bs-navbar-collapse" role="navigation"> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#">Contact</a></li> <li><a href="#">About</a></li> </ul> </nav> </div> </header> ... </body>
Listing 10. Responsive navigation markup fiddle it
It's little bad and verbose, agreed! I request you to stop here and take a good look at the markup before jumping to the next section.
6.4.4.1 Exploring the Markup
We can divide the markup (listing 10) into two sections: header (div.navbar-header) and navigation (div.navbar-collapse). The header section contains the trigger button which is used to invoke the navigation to expand or collapse in the mobile screen. The navigation section contains the unordered list of links which we saw earlier.
These two sections behave differently in case of desktop and mobile views. In case of desktop screen, the button is hidden and the navigation section is displayed. While in case of mobile view, the button is shown and navigation section is hidden as default. When you click the button the navigation shows up.
Following are some of the interesting things to keep note about the markup.
6.4.4.1.1 The role attribute
We have used a special attribute called role in two places: <header> and <nav>. The HTML5 role attribute is used for accessibility. It is used to convey screen readers and other devices about the role the corresponding element plays like banner, navigation, logo etc.
6.4.4.1.2 navbar-header
This CSS class is used to represent the header section which contains the button that is used to show the navigation in mobile screen.
6.4.4.1.3 The button element
Instead of button, you can use some other element as well. It is the CSS classes and the data attributes we've used in the element tells bootstrap "this is the element that is used to trigger to show navigation". One important data attribute I should highlight is the data-target attribute which is used to establish the connection between the button and the navigation list.
6.4.4.1.4 The sr-only attribute
The sr-only is a bootstrap attribute mainly used for accessibility. They are used in labels and other elements that render in browser but not visible to the user. They convey screen readers what role they play. You can see contact forms that contain only input fields without labels. The placeholder attribute is used to convey the user whether it is a name, email or some other. But, this UX design makes difficult for screen readers and vision impaired people. If you drop a label and make it hidden, screen readers can read aloud the input field which helps the visually impaired person to enter proper information.
6.4.5 Final touches to the Navigation header
Before wind-up, I would like to do some additional changes to the navigation header. First, I want the header to stand-out by applying a different style navbar-inverse. I also want the navigation to always stay fixed in the top, that helps me to easily navigate no matter where I'm in the page. I also want our brand name (Astrospace) to be displayed at left and a search form to be displayed at the right end as you see in the mockup.
Here we go...
<body> <header class="navbar navbar-inverse navbar-fixed-top bs-docs-nav" role="banner"> <div class="container"> <div class="navbar-header"> <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".bs-navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a href="index.html" class="navbar-brand">Astrospace</a> </div> <nav class="collapse navbar-collapse bs-navbar-collapse" role="navigation"> <form class="navbar-form navbar-right" role="search"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search"> </div> <button type="submit" class="btn btn-default">Submit</button> </form> <ul class="nav navbar-nav"> <li class="active"><a href="index.html">Home</a></li> <li><a href="contact.html">Contact</a></li> <li><a href="about.html">About</a></li> </ul> </nav> </div> </header> ... </body>
Listing 11. Responsive navigation markup final fiddle it
The navbar-inverse class gives a dark background to the navigation header. To make the bar always appear in the top, I've to apply an additional CSS class called navbar-fixed-top.
The logo, which is usually a link has to be placed in the header section. By applying the special class navbar-brand to the link, it stand-out in font-size and differentiate itself from other links. Usually we drop the logo image inside the link to reflect the brand; but to keep things simple, I've used plain text.
You can drop any element inside the <nav> element and so dropping a search form is not a big deal. But important thing is, I've to apply couple of bootstrap classes namely navbar-form and navbar-right to set the form inline and right aligned. We'll see more about bootstrap forms when we design the single post and contact pages. Don't worry about them now. For your info, I also replaced the link elements href attribute value ("#") with corresponding files.
If you run the file in browser, the navigation header appears like below in mobile and desktop.
That's awesome, isn't it? Our navigation bar is ready! It looks beautiful in both desktop and mobile with less work.
There is a small glitch! Both the div#body and footer sections are not visible. This is because we have made the header as fixed and so both the sections have moved up. To make them visible, we have to apply some top margin to the body.
Create a new style file called blog.css in the same folder and add a top margin for 75 pixels to the body. Don't forget to reference the CSS file in the index.html file.
body { margin-top: 75px; }
Listing 12. Applying top margin to body
If you refresh the page now, you can see both the <div> and <footer> elements visible. That's it, you've completed a big piece.
It's little hard to make things work in different screens, isn't it? Alright, in the coming sections, I'll introduce you grid systems and forms which are going to be pretty interesting, especially "grids"!
6.5 Create single and two-column layouts for main content and sidebar
If you re-look at mockups (Fig. 3 & 4), our main content is split into a two-column layout for desktop screen and combined into a single column in mobile screen. In case of desktop, the first column contains the latest posts and the second column contains the sidebar. While in mobile screen, the sidebar falls below the main content. Before getting into the nitty-gritty details of creating column layouts I think it's time to give you a brief about Grid Systems, a must-to-know piece!
6.5.1 Grid Systems
Grid Systems are used for creating page layouts through a series of rows and columns. Using grids helps you to visualize easily where to place a piece of content and how much space it can consume in a web page. Initially, tables are used for creating grids but once the community started to see the inflexibility they brings they avoided (hated?) them and started to use floated divs.
The 960 Grid System is the CSS framework that caught the initial attention of the web community. Now, there are many popular frameworks out there like Blueprint CSS, YAML 4, Skeleton etc. Bootstrap is one of the popular library that recently joined this club with pride. All these frameworks divide the viewport into "n" number of columns, typically, "n" is 12.
I would encourage you to learn about grids and their history. If you google "Grid Systems" you can find lot of links. I've found this one quite interesting, worth to read.
6.5.2 Bootstrap's Responsive Grid System
Bootstrap provides a 12 column grid system. If you take a desktop screen of width 1024 px, the total viewport is divided into 12 columns. The width of each column is 78px and the gutter width (gaps between column content) is 30px (15px on each side of column). The width of columns and gutters varies based upon the screen size.
Bootstrap's grid system is responsive. When I say responsive, which means, the grids adjusts or adapts based upon the screen or viewport size. For example, a single column grid designed for mobile screens can be transformed into a two column grid for tablets, desktops and as a three column grid in case of big screens like TVs, by applying proper CSS classes. Doesn't that sounds great?
Bootstrap provides different groups of CSS classes to control the layout for different screen sizes. For example, in case of desktops, they provides col-md-* (col-md-1 to col-md-12) group of classes to control the layout. To control the layout for mobiles and tablets, it provides col-xs-* and col-sm-* groups. It also provides col-lg-* classes for large screens like TVs. The middle segment of the CSS class "xs", "sm", "md" and "lg" represents the screen size (extra small, small, medium and large) and the last segment which is an integer represents the no. of columns the particular element has to span. In Bootstrap, an element can span upto 12 columns and of-course you can customize this number.
6.5.3 Simple Grid
Let's say you want to create a three-column grid for desktop screen. First, you should create a row by applying the row class to a block element like div. Inside the row element you have to create three child elements and each element should be decorated with the CSS class col-md-4. If you sum up the integer part of all the classes they equals to 12, simple rule!
<div class="row"> <div class="col-md-4">Column 1 - span 4 columns</div> <div class="col-md-4">Column 2 - span 4 columns</div> <div class="col-md-4">Column 3 - span 4 columns</div> </div>
Listing 13. Three column grid for desktop fiddle it
How does the above markup looks in the browser? Check out the below images. (Actually, I've to apply some styles to show each cell distinctively.)
What happens when you turn on emulation mode?
The grid has collapsed into a single column with all <div> elements stacked one below other and that's why it's called responsive. So when the screen size reduces below desktop size, the col-md-* classes have no effect. What if we still want the content to be displayed as three columns in tablets and mobiles? For that, you should apply the col-sm-* and col-xs-* group classes.
Let's apply the column classes for tablet and mobile screens as well.
<div class="row"> <div class="col-md-4 col-sm-4 col-xs-4">Column 1 - span 4 columns in desktops, tablets and mobiles</div> <div class="col-md-4 col-sm-4 col-xs-4">Column 2 - span 4 columns in desktops, tablets and mobiles </div> <div class="col-md-4 col-sm-4 col-xs-4">Column 3 - span 4 columns in desktops, tablets and mobiles </div> </div>
Listing 14. Three column grid for desktop, tablet and mobile fiddle it
Now, if you refresh page in mobile or tablet, you could see the three column layout is maintained. Very nice!
Offsetting, Nesting and Columns reordering
Offsetting columns
Bootstrap provides .col-md-offset-* classes to move columns to the right. These classes increase the left margin of a column by * columns. For example, .col-md-offset-4 moves .col-md-4 over four columns.
<div class="row"> <div class="col-md-4">.col-md-4</div> <div class="col-md-4 col-md-offset-4">.col-md-4 .col-md-offset-4</div> </div> <div class="row"> <div class="col-md-3 col-md-offset-3">.col-md-3 .col-md-offset-3</div> <div class="col-md-3 col-md-offset-3">.col-md-3 .col-md-offset-3</div> </div> <div class="row"> <div class="col-md-6 col-md-offset-3">.col-md-6 .col-md-offset-3</div> </div>
Listing 15. Offsetting columns fiddle it
Nesting Columns
To nest your content with the default grid, add a new .row and set of .col-md-* columns within an existing .col-md-* column. Nested rows should include a set of columns that add up to 12.
<div class="row"> <div class="col-md-9"> Level 1: .col-md-9 <div class="row"> <div class="col-md-6"> Level 2: .col-md-6 </div> <div class="col-md-6"> Level 2: .col-md-6 </div> </div> </div> </div>
Listing 16. Nesting columns fiddle it
Column ordering
Easily change the order of our built-in grid columns with .col-md-push-* and .col-md-pull-* modifier classes.
<div class="row"> <div class="col-md-9 col-md-push-3">.col-md-9 .col-md-push-3</div> <div class="col-md-3 col-md-pull-9">.col-md-3 .col-md-pull-9</div> </div>
Listing 17. Ordering columns fiddle it
I hope you have a fair understanding of Bootstrap's responsive grid system now. Shall we apply this knowledge to structure the main content?
6.5.4 Complete the main content layout
Our main content of home page is primarily divided into two things: latest posts and sidebar. If you remember the mockups, in case of mobile and tablets, we want both the latest posts section and sidebar to be displayed one below other as a single column but in case of desktops and large screens we want them to be placed aside. When they placed horizontally, we want the latest posts section to occupy 2/3rd of the total viewport size.
To accomplish this, we've to create a row element (div) under the existing "#body" (div) element with two column elements (div). The first column element is decorated with col-md-8 and the second one with col-md-4.
<div class="row"> <div class="col-md-8"> -- LATEST POSTS -- </div> <div class="col-md-4"> -- SIDEBAR -- </div> </div>
Listing 18. Main content grid
Just do a quick ckeck. Make sure the page appears as below in mobile and desktop modes.
The grid is ready. Now, we have to worry about creating HTML markup for the latest posts section and sidebar widgets.
6.6 Create the HTML markup for latest posts section
If you zoom the mockup little closer, the latest posts section can be sub-divided into three sections: heading, list of posts and pager. The list of posts section is little complicated. It contains many pieces like post title, category, tags, total comments, posted date, image and couple of paragraphs. You should also think how all these pieces are arranged and how much room each takes. Once you got this in your mind defining the HTML is not that complicated. Well with that said, let's work on those three sections starting with page heading.
6.6.1 Page heading
We can use <h1> tag for specifying the top heading of the page. Bootstrap as default applies custom styles to body and heading elements. It uses "Helvetica Neue" as the font with a base size of 14px. The font-sizes for the heading elements (<h1>, <h2>...) are calculated from the base font size. For ex., the font-size of <h1> element is floor((@font-size-base * 2.6)) which is 36px. We'll see more about this when we customize the font system in the next part.
Let's create a <h1> element under the first column div (col-md-8) with text "Latest Posts".
<div class="col-md-8"> <h1>Latest Posts</h1> ... </div>
Listing 19. Page heading
Let's work on the next item which is list of posts.
6.6.2 List of posts
Each post section is comprised of post title, category, tags, total comments, posted date, introduction paragraphs with image and a continue link.
HTML5 provides the <article> element which can be used to semantically represent each blog post, forum post, newspaper article etc., we are going to use the same. We can use the <h2> element to represent the post title. Like <h1>, bootstrap set some default style for <h2> as well.
We can use grid to arrange the category, tags, total comments and posted date elements. As shown in the mock-ups, in case of mobile screen we want the grid to collapse and the elements should fall one below other and in case of tablets and desktops we want them to align horizontally.
Considering all these factors I've created the below HTML. Please go through the HTML and I'll explain some hidden things in the "Exploring Markup" section.
<article> <h2><a href="singlepost.html">Aries Sun Sign March 21 - April 19</a></h2> <div class="row"> <div class="group1 col-sm-6 col-md-6"> <span class="glyphicon glyphicon-folder-open"></span> <a href="#">Signs</a> <span class="glyphicon glyphicon-bookmark"></span> <a href="#">Aries</a>, <a href="#">Fire</a>, <a href="#">Mars</a> </div> <div class="group2 col-sm-6 col-md-6"> <span class="glyphicon glyphicon-pencil"></span> <a href="singlepost.html#comments">20 Comments</a> <span class="glyphicon glyphicon-time"></span> August 24, 2013 9:00 PM </div> </div> <hr> <img src="http://placehold.it/900x300" class="img-responsive"> <br /> <p class="lead">Aries is the first sign of the zodiac, and that's pretty much how those born under this sign see themselves: first. Aries are the leaders of the pack, first in line to get things going. Whether or not everything gets done is another question altogether, for an Aries prefers to initiate rather than to complete. Do you have a project needing a kick-start? Call an Aries, by all means. The leadership displayed by Aries is most impressive, so don't be surprised if they can rally the troops against seemingly insurmountable odds.</p> <p>The symbol of Aries is the Ram, and that's both good and bad news. Impulsive Aries might be tempted to ram their ideas down everyone's throats without even bothering to ask if they want to know. It's these times when you may wish Aries' symbol were a more subdued creature, more lamb than ram perhaps. You're not likely to convince the Ram to soften up; these folks are blunt and to the point. Along with those qualities comes the sheer force of the Aries nature, a force that can actually accomplish a great deal. Much of Aries' drive to compete and to win comes from its Cardinal Quality. Cardinal Signs love to get things going, and Aries exemplifies this even better than Cancer, Libra or Capricorn.</p> <p class="text-right"> <a href="singlepost.html" class="text-right"> continue reading... </a> </p> <hr> </article>
Listing 20. Repeating post markup
Let's explore the markup.
6.6.2.1 Exploring Markup
6.6.2.1.1 Grid
If you see the grid, we've grouped both the category and tags into one column. The total comments and posted date are grouped into other. Both takes 50% space in case of tablets, desktops and other high screen devices, in case of mobile, they are placed one below other.
<div class="row"> <div class="group1 col-sm-6 col-md-6"> <span class="glyphicon glyphicon-folder-open"></span> <a href="#">Signs</a> <span class="glyphicon glyphicon-bookmark"></span> <a href="#">Aries</a>, <a href="#">Fire</a>, <a href="#">Mars</a> </div> <div class="group2 col-sm-6 col-md-6"> <span class="glyphicon glyphicon-pencil"></span> <a href="singlepost.html#comments">20 Comments</a> <span class="glyphicon glyphicon-time"></span> August 24, 2013 9:00 PM </div> </div>
Listing 21. Grid markup to structure post meta-data information fiddle it
One important thing that I should point you in the above markup is about the custom CSS classes "group1" and "group2". The "group1" CSS class is not important but "group2" is required to align both the total comments and published date to right in case of tablets and desktops.
@media (min-width: 768px) { /* tablets and up */ .group2 { text-align: right; } }
Listing 22. Media query to right-align total comments and published date in blog.css
6.6.2.1.2 Glyphicons
We've used glyphicons to create icons for category, tags and others.
<span class="glyphicon glyphicon-folder-open"></span>
Listing 23. Glyphicon markup
Bootstrap provides nearly 200 glyphs in "font" format. Do you know what that means? Means.. you can style them just like fonts. To increase the size of the icon all you have to do is increase the font-size. Does it sounds cool? yes, it is! Who needs image sprites for icons anymore.
To create a glyphicon, you've to create a <span> element and apply two CSS classes to it. One is the base CSS class called glyphicon which you should apply to all the icons and next one is specific to the icon like glyphicon-folder-open. We can use glyphicons with any components like buttons, button groups, navigation bars and more.
6.6.2.1.3 Responsive images
As default images are not responsive, their widths doesn't adjust based upon the screen size. Each post has an image and to make them responsive we've to apply the CSS class called img-responsive.
<img src="http://placehold.it/900x300" class="img-responsive">
Listing 24. Responsive images fiddle it
From the below images you can understand how the image applied with img-responsive class adjusts it's width based on screen size.
For people who interested in peeking the source-code, below is the definition of img-responsive class.
.img-responsive { display: block; height: auto; max-width: 100%; }
Listing 25. "img-responsive" CSS class definition
6.6.2.1.4 Decorative Classes
To make the first paragraph of post standout we've applied the CSS class called lead. Applying this class increases the font size and makes it bold.
<p class="lead"> Aries is the first sign of the zodiac, and that's pretty much how those born under this sign see themselves: first. Aries are the leaders of the pack, first in line to get things going.... <p>
Listing 26. Applying "lead" CSS class to make paragraph stand-out fiddle it
Jubmotron
Bootstrap also provides another similar class called Jumbotron which is used to highlight key content of the website.
<div class="jumbotron"> <h1>Hello, world!</h1> <p> This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.</p> <p> <a class="btn btn-primary btn-lg" role="button">Learn more</a> </p> </div>
Listing 27. Jumbotron fiddle it
6.6.2.1.5 Helper Classes
To navigate the user to full post we've provided a continue link. To align this link to right, we've wrapped it in a paragraph and applied the Bootstrap CSS class called text-right to it. All this class does is, set the style "text-align" to "right" to the element. As you might already guessed, this class is not alone it has two cousins: text-left and text-center.
<p class="text-right"> <a href="singlepost.html"> continue reading... </a> </p>
Listing 28. Markup for "continue reading" link fiddle it
pull-left and pull-right
Bootstrap provides helper classes (pull-left and pull-right) to float elements left or right. To know more about other helper classes visit this page.
That's all the hidden facts. Now they all are revealed to you.
Let's see the third and final thing: pager.
6.6.3 Pager
From the dozen of components Bootstrap provides (including navigation which we used earlier), it also provides pagination component. There are two variations available: numbers and previous/next links. We are going to try the second one. It looks like the markup is very simple!
<ul class="pager"> <li class="previous"> <a href="#">← Older</a> </li> <li class="next"> <a href="#">Newer →</a> </li> </ul>
Listing 29. Pager fiddle it
Append the above html at the end of the main column div (div.col-md-8). You could see the pager appear as below.
That's it, we've completed the markup for the main content. To keep you stay in the track, this how the body HTML should look like overall (I've removed the text inside <article> tags).
<div class="container"> <div class="row"> <div class="col-md-8"> <!-- heading --> <h1>Latest Posts</h1> <!-- list of posts --> <article> <h2><a href="singlepost.html">Aries Sun Sign March 21 - April 19</a></h2> <div class="row"> <div class="group1 col-sm-6 col-md-6"> <span class="glyphicon glyphicon-folder-open"></span> <a href="#">Signs</a> <span class="glyphicon glyphicon-bookmark"></span> <a href="#">Aries</a>, <a href="#">Fire</a>, <a href="#">Mars</a> </div> <div class="group2 col-sm-6 col-md-6"> <span class="glyphicon glyphicon-pencil"></span> <a href="singlepost.html#comments">20 Comments</a> <span class="glyphicon glyphicon-time"></span> August 24, 2013 9:00 PM </div> </div> <hr> <img src="http://placehold.it/900x300" class="img-responsive"> <br /> <p class="lead">Aries is the first sign of the zodiac�</p> <p>...</p> <p class="text-right"> <a href="singlepost.html"> continue reading... </a> </p> <hr> </article> <article> ... </article> <!-- pager --> <ul class="pager"> <li class="previous"> <a href="#">← Older</a> </li> <li class="next"> <a href="#">Newer →</a> </li> </ul> </div> <div class="col-md-4"> <!-- TODO: Sidebar --> </div> </div> </div>
Listing 30. Home page main content markup
Does your markup looks same as above? I hope the answer is "Yes". So, we've completed the markup for main content. It was little more work. The sidebar and other pages won't be this hard, promise! Let's recollect what we've done so far. We've completed the navigation header, main content and footer sections. On the way, we've learnt about many interesting things from Bootstrap: navigation and pagination components, grids, images, decorative and helper classes.
Let's take a little break. Next, we are going to work on Sidebar.
6.7 Create sidebar widgets
The Sidebar contains stack of widgets like subscribe to my feed, latest posts, categories, tags and recent comments. You may even want to add some more. All these widgets take 33% of the screen in desktops and 100% in mobile.
As a matter of fact, all these sidebar widgets should be wrapped by the second column div element (div.col-md-4), we haven't touched this element yet!
<div class="col-md-4"> <!-- Sidebar --> </div>
Listing 31. Sidebar column
Let's start working on each widget starting from the "subscribe to my feed" widget.
6.7.1 "Subscribe to my feed" widget
The subscribe widget should standout and invite users to get subscribed to the blog. We could use the jumotron CSS class but I'll introduce another one of similar kind called well. The well CSS class is used to create a simple rectangle that gives an inset effect to an element.
For ex,
<div class="well"> Look, I'm in a well! <div>
Listing 32. "well" CSS class on div fiddle it
The above markup appears as below in browser.
well-lg and well-sm
To control the padding and rounded corners of wells, Bootstrap provides couple of optional CSS classes called well-lg and well-sm.
Coming back to our widget, we need to throw some simple text and subscribe button, which changes the markup as shown below.
<div class="col-md-4"> <!-- Subscribe to my feed widget --> <div class="well text-center"> <p class="lead"> Don't want to miss updates? Please click the below button! </p> <button class="btn btn-primary btn-lg">Subscribe to my feed</button> </div> <!-- Other widgets --> </div>
Listing 33. Subscribe to my feed widget fiddle it
It's time to run the page in browser. The widget appears nearly same in desktop and mobile, but only thing in the case of mobile the widget appears below the latest posts section, expanded, taking 100% of the screen width.
Before moving to work on other widgets, I've to explain about buttons. We've already used a button in the navigation header for search form. I missed to explain about them at that time but not now. We can enhance a normal button into Bootstrap button by applying the CSS class btn.
Buttons are one of the primary components in Bootstrap. We can apply the CSS class btn to other elements like <a> or <input> and make them Bootstrap buttons. There are two supportive groups of classes available to customize the type (success, danger, warning etc.) and size (large, small, extra small etc.).
To customize the type, we've to apply btn-success, btn-danger, btn-warning or other from that group to the element along with the btn class. To customize the size we can apply btn-lg, btn-sm or btn-xs classes.
I hope we are good with buttons now. Let's continue our work on other widgets.
6.7.2 Latest posts, Categories and Recent Comments widgets
The Latest posts widget is used to display the list of latest posts. It looks similar like other widgets: Categories, Tags and Recent Comments. Each of them contains a simple heading and body. The body section contains bunch of links. Does Bootstrap provide any component to create such widgets? Yes, the answer is panel.
Panels are used to create flat widgets with border and padding. A panel contains three sections: header (panel-header), body (panel-body) and footer (panel-footer).
<div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Panel title</h3> </div> <div class="panel-body"> Panel body </div> <div class="panel-footer"> Panel footer </div> </div>
Listing 34. Panel fiddle it
We need only heading and body sections in our widgets. The body contains an unordered list of links to latest posts. As default, Bootstrap doesn't apply styles to both <ul> and <ol> elements. We can decorate them by applying the CSS class list-group. This is how the HTML markup of latest posts widget looks like,
<div class="panel panel-default"> <div class="panel-heading"> <h4>Latest Posts</h4> </div> <ul class="list-group"> <li class="list-group-item"><a href="singlepost.html">1. Aries Sun Sign March 21 - April 19</a></li> <li class="list-group-item"><a href="singlepost.html">2. Taurus Sun Sign April 20 - May 20</a></li> <li class="list-group-item"><a href="singlepost.html">3. Gemini Sun Sign May 21 - June 21</a></li> <li class="list-group-item"><a href="singlepost.html">4. Cancer Sun Sign June 22 - July 22</a></li> <li class="list-group-item"><a href="singlepost.html">5. Leo Sun Sign July 23 - August 22 </a></li> </ul> </div>
Listing 35. Latest posts widget fiddle it
This is how the latest posts widget appears in screen.
The HTML markup for Categories and Recent comments widgets also pretty much same like the former.
<div class="panel panel-default"> <div class="panel-heading"> <h4>Categories</h4> </div> <ul class="list-group"> <li class="list-group-item"><a href="#">Signs</a></li> <li class="list-group-item"><a href="#">Elements</a></li> <li class="list-group-item"><a href="#">Planets</a></li> <li class="list-group-item"><a href="#">Cusps</a></li> <li class="list-group-item"><a href="#">Compatibility</a></li> </ul> </div> <div class="panel panel-default"> <div class="panel-heading"> <h4>Recent Comments</h4> </div> <ul class="list-group"> <li class="list-group-item"><a href="#">I don't believe in astrology but still your writing style is really great! - <em>john</em></a></li> <li class="list-group-item"><a href="#">Wow.. what you said is really true! I'm an aries though - <em>Anto</em></a></li> <li class="list-group-item"><a href="#">Does capricorn and aries is compatibile? - <em>Sarah</em></a></li> <li class="list-group-item"><a href="#">I'm a cancer woman been in love with Leo. Will this work? - <em>Mary</em></a></li> </ul> </div>
Listing 36. Categories and recent comments widgets fiddle it
6.7.3 Tags widget
The Tags widget also looks like other ones but the only difference is, the links are inline instead of block. To achieve this, we've to replace the list-group class with list-inline.
<div class="panel panel-default"> <div class="panel-heading"> <h4>Tags</h4> </div> <div class="panel-body"> <ul class="list-inline"> <li><a href="#">Aries</a></li> <li><a href="#">Fire</a></li> <li><a href="#">Mars</a></li> <li><a href="#">Taurus</a></li> <li><a href="#">Earth</a></li> <li><a href="#">Moon</a></li> <li><a href="#">Gemini</a></li> <li><a href="#">Air</a></li> <li><a href="#">Mercury</a></li> <li><a href="#">Cancer</a></li> </ul> </div> </div>
Listing 37. Tags widget fiddle it
We've completed all the widgets and the sidebar.
6.7.4 Complete Footer
We are close to complete the home page of the blog. A simple piece is missing in the <footer> section of the page. We already have the <footer> section but it's not complete and it misses the copyright information and some style. Let's finish that.
<footer> <div class="container"> <hr /> <p class="text-center">Copyright © Astrospace 2014. All rights reserved.</p> </div> </footer>
Listing 38. Footer markup
I don't need to explain anything special about the above markup. You already know about the classes (container, text-center) I've used there.
To create more room for footer to breathe we need to apply a 10px margin at both top and bottom.
footer { margin: 10px 0; }
Listing 39. Styling footer (Blog.css)
By that, we've successfully completed the home page of the blog.
In the creation of the home page we've learnt many things from Bootstrap. Other than the navigation component most of the things are pretty easy. In the coming pages (singlepost, contact and about) we'll see about creating HTML forms using Bootstrap which are pretty important, so stay tuned!
7. Create the single post page
The single-post page is similar like the home page, we've to copy most of the stuff from there. The header, sidebar and footer are going to be same. Instead of list of posts, we've to display the details of a single post with a form to post comment and list of posted comments. There won't be any "continue reading" link and the pager contains a single link to go back to the home page.
Here are the mockups of single-post page for both mobile and desktop screens
The two important tasks we've to do to complete this page are:
1. Create comment form
2. Create markup to display list of posted comments
7.1 Create comment form
If you see the mockup, the comment form is very simple. All it contains are three fields and a submit button. We can wrap the comment form in a well to make it appear appealing.
<div class="well"> <h4>Leave a comment</h4> <!-- TODO: comment form --> </div>
Listing 40. Comment form container
Do you remember, we've already a HTML form in the navigation header to provide search functionality. I'm not making out, Bootstrap really provides great support for HTML forms and controls. May I brief about the support before continuing our work? I know the answer is yes, let's do it.
7.1.1 Bootstrap forms
As default, Bootstrap applies some global styling to form controls, but, we can customize them more by applying some special CSS classes. The most important CSS class that you should apply to all the textual form controls like textbox, textarea and dropdown is form-control. What this class does? It transforms the control to a block element, make it consume the entire width of the parent.
Let's create some simple forms and see what we can learn.
7.1.2 Simple forms
Here is a simple form that contains label, textbox and submit button.
<form role="form"> <label for="email">Email</label> <input type="email" class="form-control" name="email" placeholder="Enter email"> <input type="submit" value="Submit" class="btn btn-primary" /> </form>
Listing 41. Simple form fiddle it
I already told you about the role attribute applied in the <form> element, which is used for accessibility. There is nothing special about the label, though, there are couple of things I've to tell you about <input> element. It's type attribute is set to "email" which helps in validation and to change the on-screen keyboard in devices like iPhone (adds @ and .com options). The next thing is the CSS class form-control, I already told about its purpose, which you can see by running the markup in the browser.
The form-control has transformed the textbox into a block control - to fall down below the label and consume the entire page width. Let's drop more fields like checkbox, dropdown etc. and see what happens.
<form role="form"> <label for="name">Name</label> <input type="text" class="form-control" name="name" placeholder="Enter name"> <label for="email">Email</label> <input type="email" class="form-control" name="email" placeholder="Enter email"> <label for="available">Available?</label> <input type="checkbox" name="available"> <input type="submit" value="Submit" class="btn btn-primary" /> </form>
Listing 42. Simple form with more controls fiddle it
The above form contains two textboxes and one checkbox. Except the checkbox, others are decorated with form-control. You don't need to apply that class to the checkbox which makes it look ugly! Maybe, you've to see yourself how ugly it is. Anyway, what happens if you run the above HTML in browser?
The controls are placed right one below other. But, don't they looks little congested? Actually, we can group each control and the associated label by wrapping them inside a <div> with class form-group, this helps to apply a small bottom margin under each group, make them look little distinct.
<form role="form"> <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" name="name" placeholder="Enter name"> </div> <div class="form-group"> <label for="email">Email</label> <input type="email" class="form-control" name="email" placeholder="Enter email"> </div> <div class="form-group"> <label for="available">Available?</label> <input type="checkbox" name="available"> </div> <div class="form-group"> <input type="submit" value="Submit" class="btn btn-primary" /> </div> </form>
Listing 43. Simple form with groups fiddle it
Things look far better now. Let see about inline forms.
7.1.3 Inline forms
By applying only the form-control class to the controls without applying any other special classes to the form or controls, forces them to fall one below other in a vertical column. Suppose we want to place controls in a single horizontal row, how we can accomplish that? Does Bootstrap proivdes any support for inline forms?
The answer is "Yes". Bootstrap provides a family of CSS classes that can be applied to the form to customize the ways the controls are laid out. To place the controls inline, Bootstrap provides a special class called form-inline. Let's apply this class to the form shown in listing 43 and see what happens.
<form role="form" class="form-inline"> <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" name="name" placeholder="Enter name"> </div> <div class="form-group"> <label for="email">Email</label> <input type="email" class="form-control" name="email" placeholder="Enter email"> </div> <div class="form-group"> <label for="available">Available?</label> <input type="checkbox" name="available"> </div> <div class="form-group"> <input type="submit" value="Submit" class="btn btn-primary" /> </div> </form>
Listing 44. Inline form fiddle it
The controls are placed in a horizontal line. Inline forms provide better experience when the number of controls are less. If you want to hide the labels for textboxes, you can apply the class sr-only to them. Unlike textboxes, checkboxes needs labels. Bootstrap provides a special class called checkbox to layout the checkbox and the label as described in the below listing.
<form role="form" class="form-inline"> <div class="form-group"> <label for="name" class="sr-only">Name</label> <input type="text" class="form-control" name="name" placeholder="Enter name"> </div> <div class="form-group"> <label for="email" class="sr-only">Email</label> <input type="email" class="form-control" name="email" placeholder="Enter email"> </div> <div class="checkbox"> <label> <input name="available" type="checkbox"> Available? </label> </div> <div class="form-group"> <input type="submit" value="Submit" class="btn btn-primary" /> </div> </form>
Listing 45. Applying "checkbox" class fiddle it
What happens when you reduce the screen size or view the page in the emulator? The labels and controls are placed one below each other to form a single column - responsive!
Horizontal forms
There is another CSS class available called form-horizontal, which aligns the control and the associated label as a single row in desktops. In mobiles, they are placed one below other.
7.1.4 Using grids with forms
We can utilize grids to create complicated forms. The comment form we need to build contains two textboxes in first row (desktop), textarea and submit button in second and third rows respectively. To create these layouts we've to leverage grids.
7.1.5 Complete the comment form
Below is the complete markup for the comment form. There are couple of things I have to tell you about the markup. We don't need to use the row elements to create grid rows because of form-group. Also, we've to apply the clearfix utility class to the <form> element for clearing floats.
<div class="well"> <h4>Leave a comment</h4> <form role="form" class="clearfix"> <div class="col-md-6 form-group"> <label class="sr-only" for="name">Name</label> <input type="text" class="form-control" id="name" placeholder="Name"> </div> <div class="col-md-6 form-group"> <label class="sr-only" for="email">Email</label> <input type="email" class="form-control" id="email" placeholder="Email"> </div> <div class="col-md-12 form-group"> <label class="sr-only" for="email">Comment</label> <textarea class="form-control" id="comment" placeholder="Comment"></textarea> </div> <div class="col-md-12 form-group text-right"> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> </div>
Listing 46. Comment form fiddle it
If you open the single-post page in browser, you could see the below screens in emulation and normal modes.
Ok, we've completed the comment form. What's next? Complete the markup to display list of posted comments, not a big deal!
7.2 Create markup to display list of posted comments
Below the comment form, we've to display the list of posted comments. I want the commentor's name to be pulled left and the posted date-time to be pulled right. Bootstrap provides couple of utility classes pull-left and pull-right to float an element left or right, we are going to use the same. Below listing shows the complete markup.
<ul id="comments" class="comments"> <li class="comment"> <div class="clearfix"> <h4 class="pull-left">John</h4> <p class="pull-right">9:41 PM on August 24, 2013</p> </div> <p> <em>I don't believe in astrology but still your writing style is really great!</em> </p> </li> <li class="comment clearfix"> <div class="clearfix"> <h4 class="pull-left">John</h4> <p class="pull-right">9:41 PM on August 24, 2013</p> </div> <p> <em>I don't believe in astrology but still your writing style is really great!</em> </p> </li> </ul>
Listing 47. Posted comments list fiddle it
We've to create couple of CSS styles in the blog.css file to clear the margin, padding and also to set the list style to "none" for the comments list.
#comments, #comments li { margin: 0; padding: 0; } #comments li { list-style: none; }
Listing 48. CSS classes for posted comments list (blog.css)
Cool! we've completed the main tasks. I bet, you would see the below screen if you've done everything right.
We are nearly done with the single post page except... please, don't get frustrated, just a small piece � "update the pager" and we are done.
7.3 Update the pager
The pager in the home page contains two links: previous and next. In the single post page, we need a single link in the left side that takes back to the home page.
<ul class="pager"> <li class="previous"><a href="index.html">← Back to posts</a></li> </ul>
Listing 49. Back to posts link fiddle it
Alright, we are done! This page went quick isn't it? I heard what you said :)
In creating the single post page, we got a chance to explore Bootstrap forms. We've seen how to create simple forms using special Bootstrap CSS classes and complex ones using grids. Next, we are going to work on the contact page where we'll see *little more* about forms. You should not miss it.
8. Create the contact page
The contact page is crucial for any blog or website. It helps anyone to contact you. Mainly contains a form where user can fill their information like name, email, message and submit it. The contact page also has the same header and footer but no sidebar! If you like you can have a sidebar but that should contain widgets specific to contact page.
We've to erase everything inside the container <div>, soon we are going to fill it with some new stuff. Let's take a glance at the mockups first.
Super simple, isn't it? It contains a simple paragraph and a form for users to submit questions or anything. We already gained the basic knowledge in creating Bootstrap forms while developing single-post page. We are expert in creating forms now and we'll complete this in no time!
Let's start with typing the page heading inside container.
<div class="container"> <h1>Contact Me</h1> <!-- More to come --> </div>
Listing 50. Contact me page container and heading markup
For the stand-out-paragraph, we can decorate it with lead CSS class wrapped with well container. We've already seen about these classes, lead class increase the font-size of the paragraph and the well class gives an inset effect by creating a rectangle border and gradient. The combination of these both gives a striking effect intriguing users to post something.
<div class="container"> <h1>Contact Me</h1> <div class="well"> <p class="lead"> Do you have any question? Please use the below contact form and send a message. I'll reply you as quick as possible. </p> </div> <!-- contact form --> </div>
Listing 51. "well" container with "lead" paragraph fiddle it
8.1 Create contact form
In our contact form, we need to use grids to place the controls. In mobile, we want the labels and associated controls to lay one below other. In desktop, we want them aligned horizontal to each other. By applying a special CSS class called form-horizontal to the form, each form group (label and control) will behave as rows and we don't need to create extra "row" divs.
Go through the markup, there is nothing specific to explain more.
<div class="contact-form"> <form class="form-horizontal col-md-8" role="form"> <div class="form-group"> <label for="name" class="col-md-2">Name</label> <div class="col-md-10"> <input type="text" class="form-control" id="name" placeholder="Name"> </div> </div> <div class="form-group"> <label for="email" class="col-md-2">Email</label> <div class="col-md-10"> <input type="email" class="form-control" id="email" placeholder="Email"> </div> </div> <div class="form-group"> <label for="subject" class="col-md-2">Subject</label> <div class="col-md-10"> <input type="subject" class="form-control" id="subject" placeholder="Subject"> </div> </div> <div class="form-group"> <label for="message" class="col-md-2">Message</label> <div class="col-md-10"> <textarea class="form-control" id="message" placeholder="Message"></textarea> </div> </div> <div class="form-group"> <div class="col-md-12 text-right"> <button type="submit" class="btn btn-lg btn-primary">Submit your message!</button> </div> </div> </form> </div>
Listing 52. Contact form fiddle it
Shoot the page in browser and say "Good job" if you see things as below.
Hmm.. actually, what we've seen so far about forms is only tiny compared to the complete support provided by Bootstrap. It's out of scope to discuss about all of them in this workshop; though, I would like to highlight some additional things I might missed to say.
- Provides support to layout checkboxes and radio-buttons through CSS classes like checkbox, radio, checkbox-inline, radio-inline etc.
- Provides support to style disabled fields and fieldsets.
- Provides support to highlight controls on validation success, failure etc.
- Provides support to control the size of controls through CSS classes.
I may encourage you to visit this link to study more about forms, may be not now after you completed this workshop.
9. Create the about me page
Did I say about-me page is unique in its own ways? Yes, it is. Like contact page, it is also an important part of any blog or website. It usually displays basic information like photo, education, work and blah blah about the blog owner.
Unlike other pages, you may need to badly customize this to showcase important information about you for ex. awards, published books, portfolio etc. I took a simple approach just to display the published books by the blog owner. Feel free to customize the page according to your needs.
Constructing this page is much easier that it looks in the mockups. Like you did in Contact page, you've to wipe out everything under the container div.
I would like to ask you a question before we dive into coding.
How many grids we require to construct this page?
We need a grid to place the photo and the brief paragraph aside, in desktops. And also, we need a grid to place all the books in a single horizontal line (of-course in desktops). So... totally two, correct? Some may come with a different number like just 1; in this case you've avoided using grid for the placing photo and introduction para. Some may come with number 3; they may even thought of using grid to align the social buttons. You can create same layouts by different ways. My advice is, use grids at minimum, try to use special classes provided by Bootstrap wherever you can.
Let's start filling the container <div> with page heading.
<div class="container"> <h1>About Me</h1> <!-- Remaining work --> </div>
Listing 53. About-me page container
The remaining work can be split into three smaller tasks.
1. Create grid to arrange photo and introduction paragraph
2. Create html for social buttons
3. Create grid to arrange books
9.1 Create grid to arrange photo and introduction paragraph
In case of desktops and tablets, we need the photo to take 25% and the paragraph to take 75%, that means, we've to use both col-md-* and col-sm-* classes. In case of mobile screens, we are fine with both the photo and paragraph placed one below other each consuming 100%. Ok, here is the markup.
<div class="row"> <div class="col-md-3 col-sm-3"> <img class="img-thumbnail img-responsive photo" src="http://placehold.it/300x350" /> </div> <div class="col-md-9 col-sm-9"> <p> Hi my real name is John Rumour. I've been learning astrology for last 20 years. Yeah, that's true. Sometimes I used to think this is all bullshit. But still I love doing more research on this. Do you know why? I don't know. May be I don't know how to pass time other ways. I've predicted the future for Bill Clinton, George Bush and Osama Binladen. Everything happened as I said. I've even predicted the future for me and unfortunately it's not going like that way.. he hee. </p> <p> I don't know how to fill this paragraph more, so, Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. </p> </div> </div>
Listing 54. Grid markup to arrange photo and introduction paragraph fiddle it
9.1.1 Image CSS classes
Did you notice the <img> tag that is used to display the blog author's photo? We've applied two special CSS classes: img-thumbnail and img-responsive. We already saw about img-responsive class, it's used to adjust an image's dimension based on screen size. What's this new img-thumbnail class? What its purpose?
Bootstrap provides set of CSS classes to customize the border of an image. The img-thubmnail class provides a rectangle border giving a classic photo look to the image.
Image Shapes
Finally, I need a tad margin at the image bottom; so, I've added another custom CSS called photo.
.photo { margin-bottom: 10px; }
Listing 55. Applying bottom margin to image
That's it, we are done with the first grid and task.
9.2 Create html for social buttons
We need the two social buttons to be centre aligned irrespective of screen size. We can accomplish this by wrapping them in a block element with class text-center.
<p class="social-buttons text-center"> <button type="button" class="btn btn-primary btn-lg">Visit my Facebook page</button> <button type="button" class="btn btn-default btn-lg">Follow me on Twitter</button> </p>
Listing 56. Markup for social buttons fiddle it
In small screens, the buttons lay one above other giving a feel they are attached to each other. By adding a small margin over each button we can make things looks better and for that I've created a new style in blog.css file.
.social-buttons button { margin-top: 5px; }
Listing 57. Applying style to social buttons
9.3 Create grid to arrange books
We've reached the final piece: grid to arrange published books. In desktop screens, we want the books are arranged in a single row while in smaller screens, we want them to be arranged in a single column. If you remember the mockup, before the grid, there exists a small paragraph with text "For my sin, I've written the following interesting books". The paragraph has to be bold and centre-aligned; we can easily accomplish this by decorating it with lead and text-center CSS classes.
Coming to the grid, we can create it by dropping a single row <div> element which contains three column <div> elements decorated with col-md-4 class.
<div class="row"> <div class="col-md-4"></div> <div class="col-md-4"></div> <div class="col-md-4"></div> </div>
Listing 58. Grid markup to arrange books
If you see the mockup, each book image has a rectangle border with title, price and a "buy now" link (probably to Amazon) at the bottom. We could able to create this structure using panels but I would like to simplify the job by introducing another wonderful class called thumbnail, which is just made for it. This thumbnail class is specially created to easily display grids of images, videos, text, and more. See the complete markup and you'll get a better understanding.
<div class="row"> <div class="col-md-4"> <div class="thumbnail"> <a href="#"> <img src="http://placehold.it/300x450" class="img-responsive" /> </a> <div class="caption text-center"> <h4>Signs and compatabilities</h4> <p> Rs. 1200 only </p> <button class="btn btn-sm btn-success">buy now!</button> </div> </div> </div> <div class="col-md-4"> <div class="thumbnail"> <a href="#"> <img src="http://placehold.it/300x450" class="img-responsive" /> </a> <div class="caption text-center"> <h4>All About Astrology</h4> <p> Rs. 1200 only </p> <button class="btn btn-sm btn-success">buy now!</button> </div> </div> </div> <div class="col-md-4"> <div class="thumbnail"> <a href="#"> <img src="http://placehold.it/300x450" class="img-responsive" /> </a> <div class="caption text-center"> <h4>Why believe in astrology?</h4> <p> Rs. 1200 only </p> <button class="btn btn-sm btn-success">buy now!</button> </div> </div> </div> </div>
Listing 59. Complete grid markup fiddle it
Each thumbnail <div> contains an image link following with the special caption <div> used to display some meta-data about the image.
We've completed all the tasks of the About-me page. No further explanation required, run the page in browser and you should the below screens in both desktop and mobile modes.
Congratulations! We've completed the design & construction for all the pages that we planned for our blog template. Feel free to download the template from the attached download link or fork it in Git.
10. Summary
That was like a nice tour, isn't it? I hope you enjoyed it. In constructing all those four pages, we've learn't many interesting things from Bootstrap. In creating the home page, we saw about bootstrap components and amazed how easily we can roll out a navigation header that delivers best user experience for both desktop and mobile users. We also surprised by seeing the power of Grid Systems and how easily we can control the structure for each screen by applying proper CSS classes.
While we were working on single-post and contact pages, we discussed about the Bootstrap support for HTML forms and their controls. Now, we have a nice blog template that we can use right away! But, keep in mind, this is just a part of story. We are going to try some pretty cool things in the next part, where we'll customize the template and make people wonder, "Are they really used Bootstrap to create this?".
Before you leave, may I ask you something. Please post a comment, it could be an appreciation, suggestion or improvement. I'll take your feedback in a considered manner and take necessary steps. Thanks for reading!