如何在Bootstrap 4中修改列的数量?
Got it, let's break down how to change the number of columns in Bootstrap 4! By default, Bootstrap uses a 12-column grid system, but you can tweak this to fit your project's needs with two main approaches—using Sass (the official, most flexible way) or overriding styles with custom CSS. Here's a step-by-step look at both:
This is the best approach if you're working with Bootstrap's source Sass files (not just the pre-compiled CSS). It lets you fully integrate the custom column count into Bootstrap's core styles.
- First, make sure your project is set up to compile Bootstrap's Sass code.
- Locate the
_variables.scssfile in Bootstrap's source files. Find the$grid-columnsvariable—its default value is12. - Modify it to your desired column count, like 16:
$grid-columns: 16; // Replace with any number you need (e.g., 10, 24) - Optional: Adjust the gutter (spacing between columns) by updating the
$grid-gutter-widthvariable:$grid-gutter-width: 20px; // Default is 30px, tweak based on your design - Recompile Bootstrap's Sass code to generate your custom CSS file.
- Now you can use the new column classes seamlessly, like
col-4(takes up 4/16 of the row width) orcol-lg-12(takes up 12/16 on large screens). All responsive breakpoint classes will automatically adapt to your new column count.
If you don't want to mess with Sass compilation, you can directly override Bootstrap's default styles with custom CSS. Let's use 16 columns as an example:
- First, set consistent spacing for rows and columns:
.row { margin-right: -10px; margin-left: -10px; } .col, [class*="col-"] { padding-right: 10px; padding-left: 10px; } - Define the width for each column (calculated as
100% / your-column-count):/* Base mobile-first columns */ .col-1 { width: 6.25%; } .col-2 { width: 12.5%; } .col-3 { width: 18.75%; } .col-4 { width: 25%; } .col-5 { width: 31.25%; } .col-6 { width: 37.5%; } .col-7 { width: 43.75%; } .col-8 { width: 50%; } .col-9 { width: 56.25%; } .col-10 { width: 62.5%; } .col-11 { width: 68.75%; } .col-12 { width: 75%; } .col-13 { width: 81.25%; } .col-14 { width: 87.5%; } .col-15 { width: 93.75%; } .col-16 { width: 100%; } - Add responsive breakpoints if needed (e.g., for medium screens):
@media (min-width: 768px) { .col-md-1 { width: 6.25%; } .col-md-2 { width: 12.5%; } /* Repeat for all 16 column sizes */ .col-md-16 { width: 100%; } } - Note: If you use offset classes (like
offset-*), you'll need to override those too. For example,.offset-1would needmargin-left: 6.25%.
Once you've set up either method, you can use the custom column system like this:
<div class="container"> <div class="row"> <div class="col-4 bg-light p-3">4/16 Width</div> <div class="col-8 bg-secondary text-white p-3">8/16 Width</div> <div class="col-4 bg-light p-3 mt-3">Another 4/16 Width</div> </div> </div>
内容的提问来源于stack exchange,提问作者Humam HD

