The offset
classes in Bootstrap allow you to add spacing to the left of a column by shifting it horizontally. This is useful when you want to center or space out columns without using custom CSS.
Here’s a basic layout with two columns, without any offsets:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Before Bootstrap Offset Class</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-4">
<h2>Column 1</h2>
<p>This is the first column.</p>
</div>
<div class="col-4">
<h2>Column 2</h2>
<p>This is the second column.</p>
</div>
</div>
</div>
</body>
</html>
In this example, both columns take up 4 units of space (out of 12) and are side by side. There is no space or margin between the columns or to the left.
Let’s add some spacing to the left of Column 2 by using the offset
class.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>After Bootstrap Offset Class</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-4">
<h2>Column 1</h2>
<p>This is the first column.</p>
</div>
<div class="col-4 offset-4">
<h2>Column 2</h2>
<p>This is the second column with an offset.</p>
</div>
</div>
</div>
</body>
</html>
offset-4
shifts Column 2 to the right by 4 columns, creating empty space on the left.- The layout now looks like this:
- Column 1 occupies the first 4 units of space.
- There are 4 empty units (due to the
offset-4
). - Column 2 occupies the remaining 4 units.
This results in a visually spaced-out design where the second column starts further to the right. You can adjust the offset value depending on how much space you want.
You can also make offsets responsive by using classes like offset-md-4
to only apply the offset on medium or larger screens:
<div class="row">
<div class="col-4">
<h2>Column 1</h2>
<p>This is the first column.</p>
</div>
<div class="col-4 offset-md-4">
<h2>Column 2</h2>
<p>This column is only offset on medium or larger screens.</p>
</div>
</div>
This way, the offset only applies on larger screens, but on smaller screens, both columns will take their natural positions.