Bootstrap 4: выравнивание динамически добавляемых столбцов

Я пытаюсь использовать сетку bootstrap 4. Количество столбцов варьируется по количеству и добавляется динамически. Это приводит к добавлению более 12 столбцов в строку (что не идеально, но не знаю, как поступать в таких сценариях, когда столбцы добавляются динамически).

Результат: сетка работает нормально и переставляет столбцы, как и ожидалось. Однако я думаю, что желоб добавляется дважды для внутренних столбцов. Обратитесь к приложенному изображению.

Я искал документы, использовал justify-space-between/around - но не повезло

https://jsfiddle.net/8L3dt1xh/1/

<div class="row">
  <div class="col-lg-2 col-md-3 col-sm-4 col-6"> .. image .. </div>
  <div class="col-lg-2 col-md-3 col-sm-4 col-6"> .. image .. </div>
  ... many such divs .. 
  <div class="col-lg-2 col-md-3 col-sm-4 col-6"> .. image .. </div>
  <div class="col-lg-2 col-md-3 col-sm-4 col-6"> .. image .. </div>
</div>

Любой указатель на то, как получить равномерное расстояние между столбцами, будет большим подспорьем.

введите здесь описание изображения


person Soumya    schedule 15.08.2020    source источник
comment
Покажите нам, что внутри каждого столбца. Я не думаю, что желоб будет двойным. Зазор, который вы видите, может быть связан с элементами после изображений.   -  person David Liang    schedule 15.08.2020
comment
@DavidLiang Добавил JSfiddle в пост. Пожалуйста, чек   -  person Soumya    schedule 15.08.2020


Ответы (2)


Другой способ — добавить отступ 15px к обеим сторонам контейнера, что даст согласованный результат во всех строках, независимо от количества элементов.

.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>

person Akber Iqbal    schedule 15.08.2020

Я лично предпочел бы создать flexbox самостоятельно, а не использовать систему сетки Bootstrap, потому что тогда я могу добавить свои собственные отступы к элементам и рассчитать равномерное расстояние между ними.

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

Прежде всего, вы хотите сделать .items флексбоксом, отображаемым в виде переносимой строки:

@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;
}

Здесь я использую SASS, но вы можете увидеть сгенерированный CSS в демо.

Я также видел, что у вас есть классы .col-6, .col-sm-4 и т. д. в каждом столбце. Вы можете воспроизвести это, установив ширину .item для каждой точки останова:

@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
        }
    }
}

Теперь пришло время рассчитать желоб между двумя .items. Действительно, если вы добавите отступы к каждому .item, интервал между двумя из них будет удвоен. Но вы можете легко приспособиться к этому, добавив половину желоба/промежутка в их родительском флексбоксе, .items.

Было бы еще проще, если бы вы использовали SASS, потому что вы можете объявить переменную для желаемого расстояния между желобами и выполнять вычисления на ее основе:

@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
        }
    }
}

Это добавит 1rem padding к flexbox .items и 1rem padding к каждому .item. Это составит всего 2rem отступов вокруг каждого элемента.

введите здесь описание изображения


демонстрация: https://jsfiddle.net/davidliang2008/rv0knh8b/15/

person David Liang    schedule 16.08.2020