Details
Most of Bootstrap’s functionality is based around CSS classes. If you’re going to use Bootstrap’s grid system, there are three CSS classes you need to know: container
, row
, and col
.
There are also four rules you need to know that are associated with these classes:
- “Containers are the most basic layout element in Bootstrap and are required when using our default grid system.”
- “In a grid layout, content must be placed within columns…”
- “…only columns may be immediate children of rows.”
- Bootstrap is based on a 12 column system.
These rules result in the following basic structure for the grid system:
<div class="container">
<div class="row">
<div class="col">
One of three columns
</div>
<div class="col">
One of three columns
</div>
<div class="col">
One of three columns
</div>
</div>
</div>
First, notice that the container div is wrapping the row div (rule 1). If you’re using a row div inside your code, you need to make sure it’s inside of a container div. Note that containers can have other direct children besides row divs.
Next, notice how the text content is inside of the col divs, and not the row div (rule 2). Also, notice that the col divs are direct children of the row div (rule 3). In this example, since there are three columns, they each take up 4 spaces, adding up to 12 spaces total (rule 4). There are other column classes you can use to specify certain column widths instead of distributing the space evenly.
Anti-patterns
To further illustrate these rules, here are some code samples that show how NOT to use Bootstrap.
This code sample is not using a container, breaking rule 1:
<div class="row">
<div class="col">
One of three columns
</div>
<div class="col">
One of three columns
</div>
<div class="col">
One of three columns
</div>
</div>
This code sample has content outside of a col div, breaking rule 2:
<div class="container">
<div class="row">
TEXT OUTSIDE COL DIV
<div class="col">
Text inside col div
</div>
<div class="col">
Text inside col div
</div>
</div>
</div>
This code sample has a Bootstrap card div as a direct child of a row, breaking rule 3:
<div class="container">
<div class="row">
<div class="card">
<div class="card-body">
This is some text within a card body.
</div>
</div>
<div class="col">
One of three columns
</div>
<div class="col">
One of three columns
</div>
</div>
</div>
This code sample has two divs with col classes that add up to be greater than 12 spaces, so the second column gets pushed onto a new row in the browser window:
<div class="container">
<div class="row">
<div class="col-10">
This column takes up 10 spaces.
</div>
<div class="col-4">
This column takes up 4 spaces.
</div>
</div>
</div>
If you want your columns to stay on one row, make sure the spaces they take up adds up to 12 or less.
Exercises
There are no exercises for this lesson.