Bootstrap 4: How to align columns that are added dynamically

Trying to implement the bootstrap 4 grid system with a dynamic number of columns being added to a row, sometimes exceeding the 12-column limit. Despite the grid rearranging correctly, it seems like there is a double gutter issue for the inner columns. The challenge lies in maintaining consistent spacing between the columns.

Various attempts have been made, including using justify-space-between/around classes, but the issue persists. Refer to the attached image for a visual representation.

If you have any insights or suggestions on achieving uniform spacing between columns in such scenarios, please share. Your input would be greatly appreciated.

Sample code snippet on JSFiddle

<div class="row">
  <div class="col-lg-2 col-md-3 col-sm-4 col-6"> .. content .. </div>
  <div class="col-lg-2 col-md-3 col-sm-4 col-6"> .. content .. </div>
  ... additional columns ...
  <div class="col-lg-2 col-md-3 col-sm-4 col-6"> .. content .. </div>
  <div class="col-lg-2 col-md-3 col-sm-4 col-6"> .. content .. </div>
</div>

Reference image

Answer №1

One option is to include a padding of 15px on both sides of the container, ensuring a consistent outcome across all rows, regardless of the number of items

.row {
  padding: 0 15px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

<section class="">
  <div class="container-fluid">
    <div class="row">
      <div class="col-lg-2 col-md-3 col-sm-4 col-6">
        <a href="/">
          <figure class="figure">
            <img src="https://via.placeholder.com/850X150?text=X" style="height:150px" class="img-fluid rounded" alt="dummy">
            <figcaption class="figure-caption text-center">Check</figcaption>
          </figure>
        </a>
      </div>
      <div class="col-lg-2 col-md-3 col-sm-4 col-6">
        <a href="/">
          <figure class="figure">
            <img src="https://via.placeholder.com/850X150?text=X" style="height:150px" class="img-fluid rounded" alt="dummy">
            <figcaption class="figure-caption text-center">Check</figcaption>
          </figure>
        </a>
      </div>
      <div class="col-lg-2 col-md-3 col-sm-4 col-6">
        <a href="/">
          <figure class="figure">
            <img src="https://via.placeholder.com/850X150?text=X" style="height:150px" class="img-fluid rounded" alt="dummy">
            <figcaption class="figure-caption text-center">Check</figcaption>
          </figure>
        </a>
      </div>
      <div class="col-lg-2 col-md-3 col-sm-4 col-6">
        <a href="/">
          <figure class="figure">
            <img src="https://via.placeholder.com/850X150?text=X" style="height:150px" class="img-fluid rounded" alt="dummy">
            <figcaption class="figure-caption text-center">Check</figcaption>
          </figure>
        </a>
      </div>
      <div class="col-lg-2 col-md-3 col-sm-4 col-6">
        <a href="/">
          <figure class="figure">
            <img src="https://via.placeholder.com/850X150?text=X" style="height:150px" class="img-fluid rounded" alt="dummy">
            <figcaption class="figure-caption text-center">Check</figcaption>
          </figure>
        </a>
      </div>
      <div class="col-lg-2 col-md-3 col-sm-4 col-6">
        <a href="/">
          <figure class="figure">
            <img src="https://via.placeholder.com/850X150?text=X" style="height:150px" class="img-fluid rounded" alt="dummy">
            <figcaption class="figure-caption text-center">Check</figcaption>
          </figure>
        </a>
      </div>
      <div class="col-lg-2 col-md-3 col-sm-4 col-6">
        <a href="/">
          <figure class="figure">
            <img src="https://via.placeholder.com/850X150?text=X" style="height:150px" class="img-fluid rounded" alt="dummy">
            <figcaption class="figure-caption text-center">Check</figcaption>
          </figure>
        </a>
      </div>
    </div>
  </div>
</section>

Answer №2

Personally, I prefer constructing my own flexbox rather than relying on Bootstrap's Grid system. This way, I have the freedom to customize padding on items and ensure a consistent spacing between them.

<section class="items">
    <a href="#" class="item">
        <figure />
    </a>
    <a href="#" class="item">
        <figure />
    </a>
    ...
</section>

To begin, set .items as a flexbox with a row that wraps:

@import "../node_modules/bootstrap/scss/functions";
@import "../node_modules/bootstrap/scss/variables";
@import "../node_modules/bootstrap/scss/mixins";

.items {
    display: flex;
    flex-flow: row wrap;
}

I'm utilizing SASS here but the generated CSS is visible in the demo.

I noticed the .col-6, .col-sm-4, etc classes on each column. You can mimic this by adjusting the width of each .item on different breakpoints:

@import "../node_modules/bootstrap/scss/functions";
@import "../node_modules/bootstrap/scss/variables";
@import "../node_modules/bootstrap/scss/mixins";

.items {
    display: flex;
    flex-flow: row wrap;

    .item {
        width: calc(100%/2);        // 2 per row 

        @include media-breakpoint-up(sm) {
            width: calc(100%/3);    // 3 per row
        }

        @include media-breakpoint-up(md) {
            width: calc(100%/4);    // 4 per row
        }

        @include media-breakpoint-up(lg) {
            width: calc(100%/6);    // 6 per row
        }
    }
}

Next, calculate the gutter between two .items. Even with padding on each .item, the spacing between them will double. To compensate, add half of the gutter/spacing on the parent flexbox, .items.

If you are using SASS, defining a variable for the gutter spacing and conducting calculations based on that would simplify the process:

@import "../node_modules/bootstrap/scss/functions";
@import "../node_modules/bootstrap/scss/variables";
@import "../node_modules/bootstrap/scss/mixins";

$items-gutter: 2rem;

.items {
    display: flex;
    flex-flow: row wrap;
    padding: $items-gutter/2;

    .item {
        padding: $items-gutter/2;
        width: calc(100%/2);        // 2 per row 

        @include media-breakpoint-up(sm) {
            width: calc(100%/3);    // 3 per row
        }

        @include media-breakpoint-up(md) {
            width: calc(100%/4);    // 4 per row
        }

        @include media-breakpoint-up(lg) {
            width: calc(100%/6);    // 6 per row
        }
    }
}

This setup adds 1rem padding on the .items flexbox and 1rem padding on each .item, totaling 2rem of padding around each item.

https://i.sstatic.net/M3TUJ.png


demo: https://jsfiddle.net/davidliang2008/rv0knh8b/15/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing jQuery to incorporate a radio input function in a POST request

When the Index.php page button is pressed, data is sent to the Resultx.php script page, which then responds with an asynchronous call back on the same Index.php page. index.php <script> $(document).ready(function() { $("#input_form").subm ...

Eliminate the unnecessary gap below the image

I have noticed that there is too much space beneath an image on my website. I have tried checking for extra tags, but I suspect that it might be controlled in a css file. Could someone please help me identify which part of the css is causing this extra ...

Can I use javascript/jquery to alter the direction of text in each line?

Looking for assistance with changing text direction on each new line. For instance: text left-to-right text right-to-left text left-to-right text right-to-left... etc. I would like the text direction to change with each word-wrap: break-word. Any help w ...

Is there a way to track the number of visits by a 'user' to a website?

Looking to hide certain parts of my website from users who have visited more than a specified number of times. The NY Times site has something similar. Utilizing react & firebase for this project. Considered using IP addresses, but it seems to identify l ...

The compiler throwing an error claiming that the indexOf method is not a valid

Currently, I am working on a simple form that collects user input and aims to validate the email field by checking for the presence of "@" and "." symbols. However, every time I attempt to run it, an error message stating that indexOf is not a function p ...

Is there a way to set an absolute placement for <tr> tags within a <table> using Html and Css?

Struggling to position the rows in my table vertically for CSS animations. I'm having difficulty ensuring the correct width for the rows. Here's what I have so far: <!DOCTYPE html> <html> <head> <style> table { ...

Increase the spacing between elements in a row using Bootstrap's margin utility

I am working with Bootstrap and have a row class containing three different elements. I want to create a margin of 20px between each element in the row container while keeping them all on the same line. Currently, when I add a margin class with a parameter ...

What is the best way to create a function that automatically resumes audio playback 3 seconds after the pause button is clicked?

I am looking to develop a basic webpage with an autoplay audio feature. The page would include a "pause" and "play" button. I aim to implement a function where clicking the "pause" button would stop the audio, but after 3 seconds, it would automatically re ...

The Bootstrap 4-alpha.6 Jumbotron is failing to display correctly or appear as expected

While I have successfully compiled the full source of Bootstrap using Gulp, NPM, and Bower, I am encountering an issue with getting the jumbotron to display properly. Despite my efforts, the jumbotron does not appear on the page, not even the text. Initia ...

Linking a button to a (click) event within HTML content fetched from the backend

Hey there, I'm facing a scenario where I have an angular service that sends a HTTP request to the backend for some HTML code. Once the HTML is received, I'm inserting it into the component's HTML using <div [innerHTML]="..."/>. The iss ...

Enhancing WordPress Icons for Parent and Child Elements

I am seeking to customize icons on a WordPress website. The site contains a variety of product categories, including subcategories. https://i.sstatic.net/sTm1O.png My goal is to display one icon for parent categories and a different icon for child catego ...

To create a complete layout without relying on fixed positioning, ensure that the header, container, and footer collectively

Is there a method to ensure the header, container, and footer encompass the entire layout without using fixed positioning in CSS? Check out this HTML fiddle for reference. <div class="wrapper"> <header> <img src="https://www.ecobin.co ...

Is there a glitch with the External Style Sheet in the CodeIgniter PHP framework?

I inserted the following code into my search.php view page, which had an external style sheet. To include the style sheet in this file, I used: <head> <link rel="stylesheet" type="text/css" href="mystyle.css" /> </head> However, it doe ...

The getElementByID function functions properly in Firefox but does encounter issues in Internet Explorer and Chrome

function switchVideo() { let selectedIndex = document.myvid1.vid_select.selectedIndex; let videoSelect = document.myvid1.vid_select.options[selectedIndex].value; document.getElementById("video").src = videoSelect; } <form name="myvid1"> <s ...

Styling errors in AngularJS validation code

I am facing an issue with the code below that generates 3 text boxes. When I click on one text box, all 3 of them get focused, despite having different name and label values. <div class="col-md-12" data-ng-repeat="dohPolicy in [1,2,3]"> <div ...

choosing a specific element with jQuery to be used for future purposes

I'm having some trouble with the following code snippet: var star = $("._container > favorite"); var symbol = $(star.parentNode.parentNode).attr("symbol"); var exchange = $(star.parentNode.parentNode).attr("exchange"); After running ...

Customize the size of innerWidth and innerHeight in your THREEjs project

Is there a way to customize the size of the window where this function launches instead of it automatically calculating the height and width? I've attempted to modify this section of the code, but haven't had any success so far: renderer.setSiz ...

The seamless flow of web design

Seeking guidance on creating a responsive web page. I have a functional website that looks great on my 13" MacBook, but encounters distortion at different screen sizes. What steps are necessary to ensure it appears crisp and appealing on any device? Should ...

Clicking on the Primary Division

Experimenting with the onclick event on a parent div led me to realize that making the entire div clickable at 100% width is not what I intended. I only wanted the sub div to trigger a specific function. Here's an example: <div id="loginContain ...

modify the final attribute's value

Hello I've been using skrollr js to create a parallax website. However, the issue arises when determining the section height, as it depends on the content within. My goal is to locate the last attribute and adjust the number value based on the section ...