Multi-column layouts are a common requirement when building building HTML web sites or applications. In the old days, we would just use an HTML table and be done with it. But, these days using CSS for layout is the preferred approach. Using HTML tables for layout is considered a bad idea. Bootstrap provides an easy way to create a two column layout.
Create the two column layout: The Old Way
If I were using HTML tables to create a two column layout, I'd do something like this:
2 <tr>
3 <td>Label</td>
4 <td><input type="text" /></td>
5 </tr>
6 <tr>
7 <td>Some Other Label</td>
8 <td><input type="text" placeaholder="second text" /></td>
9 </tr>
10</table>
This is an HTML table with two rows, and two cells in each row. This is simple, but the HTML can get complex if you are nesting tables to get specific layouts. When I started building HTML sites; this was the defacto standard for complex layouts.
Nowdays, CSS is considered superior for layout purposes than using lots of nested tables, and Bootstrap is a great framework to help you do that.
Import Bootstrap
The first step is to import the Bootstrap library into your HTML page. Bootstrap is primarily a CSS library, but also has a JavaScript portion. For the purposes of this article, we just need the CSS:
Now all of the Bootstrap CSS is available to our application.
The Bootstrap Grid System
Bootstrap includes styles for a grid system consisting of rows and up to 12 columns. These are the associated styles:
- row
- Col-md-1
- Col-md-2
- Col-md-3
- Col-md-4
- Col-md-5
- Col-md-6
- Col-md-7
- Col-md-8
- Col-md-9
- Col-md-10
- Col-md-11
- Col-md-12
The first style, row, is used to dictate a row in the grid. Inside the row; you would use some combination of the column styles to dictate the length of your cell; across a 12 column row. The col-md-1 style would span across a single column. The col-md-6 style would span across 6 columns. The col-md-12 style would spread across 12 columns, or a whole row. When putting together layouts with this approach, I like to make sure the total number of cells matches 12 for each row.
Create the two column layout: With Bootstrap
Bootstrap styles can be used to create a similar layout to the one created earlier, with a table. First, create the Bootstrap row:
2</div>
Inside the row, we can create two separate columns. For the purposes of this article, both will use col-md-6, meaning each column will span 6 cells, totaling 12 cells:
2 Label
3 </div>
4 <div class="col-md-6">
5 <input type="text" />
6 </div>
The reason for making sure that the total number of columns used is equal to 12 is so that the next row will be placed under the first row; instead of next to it.
We can use the same approach for the second row:
2 <div class="col-md-6">
3 Some Other Label
4 </div>
5 <div class="col-md-6">
6 <input type="text" placeaholder="second text" />
7 </div>
8</div>
Final Thoughts
The Bootstrap Grid system can be very powerful, especially when dealing with nested layout elements.