【问题标题】:How to fix grid when there are columns of different sizes?当有不同大小的列时如何修复网格?
【发布时间】:2018-02-23 17:41:05
【问题描述】:

我已经构建了一个自定义网格,其内容类似于Creating Your Own CSS Grid System 上的内容。

当我尝试将两行中的四个项目显示为每列两列时(tablet-col-6),前两个项目将正确对齐,但第三个项目将未对齐,第四个项目位于另一行.这主要是由于每列的列具有不同的高度。不能使用 Bootstrap 的网格系统。

我该如何解决这个问题?

.container {
  width: 100%;
  max-width: 1200px;
}

.container * {
  box-sizing: border-box;
}

.row:before, 
.row:after {
  content:"";
  display: table;
  clear:both;
}

[class*='col-'] {
  float: left;
  min-height: 1px; 
  padding: 16px;
}

@media screen and (min-width: 320px) {
 .mobile-col-12 {
  width: 100%;
 }
}

@media screen and (min-width: 768px) {
 .tablet-col-6 {
  width: 50%;
 }
}

@media screen and (min-width: 1200px) {
 .desktop-col-12 {
  width: 25%;
 }
}

.border  {
  border: 1px solid black;
}
<div class="container outline">
<div class="row">
<div class="mobile-col-12 tablet-col-6 desktop-col-3 border">Compellingly expedite intermandated paradigms via out-of-the-box architectures. Enthusiastically transition vertical networks after multimedia based best practices. Completely predominate principle-centered.</div>
<div class="mobile-col-12 tablet-col-6 desktop-col-3 border">Enthusiastically benchmark cooperative information through proactive methods of empowerment. Completely syndicate alternative.</div>
<div class="mobile-col-12 tablet-col-6 desktop-col-3 border">Progressively recaptiualize quality convergence through extensive innovation. Uniquely utilize.</div>
<div class="mobile-col-12 tablet-col-6 desktop-col-3 border">Proactively pursue quality leadership skills with innovative processes. Quickly actualize dynamic.</div>
</div>
</div>

电流输出

期望的输出

【问题讨论】:

标签: css html grid


【解决方案1】:

有几件事需要解决:

  • 媒体查询中的选择器丢失 . 例如将mobile-col-12 替换为.mobile-col-12

  • 清除行中每个第一项的浮动。如果需要,您必须取消之前在不同断点内的清除。

以下是媒体查询的更新部分:

@media screen and (min-width: 320px) {
  .mobile-col-12 {
    width: 100%;
  }
}

@media screen and (min-width: 768px) {
  .tablet-col-6 {
    width: 50%;
  }
  .tablet-col-6:nth-child(2n + 1) {
    clear: both; /*clear floats*/
  }
}

@media screen and (min-width: 1200px) {
  .desktop-col-3 {
    width: 25%;
  }
  .desktop-col-3:nth-child(n) { {
    clear: none;  /*cancel clearing*/
  }
}

codepen

浮动在创建布局时已经过时,请考虑使用 Flexbox、CSS Grid 代替。

【讨论】:

  • 很好地抓住了错字,我将转换为 flexbox,并在完成后尝试提供更新
  • 不要将您当前的问题更新到 flexbox,如果您需要任何帮助,请提出一个新问题。
  • 我将您的答案标记为正确,因为它解决了我的问题。我为 flexbox 帮助创建了另一个问题 (stackoverflow.com/questions/48955434/…)。
【解决方案2】:

让我们尝试一个简单的实验,将基于 flexbox 的等高列添加到 Bootstrap 的网格系统中。

该行使用this example's CSS 中定义的自定义.row-eq-height 类使其所有列自动具有相同的高度。

所有列将垂直拉伸以占据与最高列相同的高度,因此下一列将完全左对齐。

【讨论】:

  • 显然您没有在问题中阅读此内容:不能选择使用 Bootstrap 的网格系统。
  • 糟糕,我的错误,我没有注意到...但也可以对某人有用:)
  • @Stickers 我将尝试使用 flexbox 进行转换,并将很快提供更新,感谢您阅读我的问题,因为我正在尝试寻找 Bootstrap 网格系统的替代方案
猜你喜欢
  • 2019-09-05
  • 1970-01-01
  • 2015-04-01
  • 1970-01-01
  • 2021-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多