javascript - 根据div的最大高度排列元素

标签 javascript jquery html css

我想根据 div 的最大高度排列 li,如果有更多元素,则元素自动设置在右侧。

喜欢,

-------------
  1   4  7
  2   5  8
  3   6
-------------

建议我使用 css 或使用 js 的更好方法。

我试过了,但它不能正常工作。

ul {
  column-count: 2;
  column-gap: 0;
  width: 200px;
}
li {
  display: inline-block;
  width: 100px;
  height: 100px;
  background:
    linear-gradient(
      rgba(255,0,0,0.4),
      rgba(255,0,0,0.4)
    ),
    url(http://placekitten.com/g/100/100);
  color: white;
  text-align: center;
  font-size: 50px;
  line-height: 100px;
  font-weight: bold;
  border: 1px solid white;
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
</ul>

最佳答案

来自 CSS tricks - Guide to Responsive-Friendly CSS Columns :

Use column-count and column-width together for the best control over CSS columns. You can declare each property or use the shorthand columns.

When both properties are declared, column-count is the maximum number of columns and column-width is the minimum width for those columns.

但是您没有最大列数,更像是最大高度,这似乎效果不佳。


使用 flexbox 及其多行换行魔术(编辑:此处为多 :),它可以是一个或另一个相反),您会得到预期的结果:

ul {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  /* and then define:
  - flex-flow
  - align-items (vertically here)
  - align-content maybe (horizontally here)
  according to your style needs
  => https://css-tricks.com/snippets/css/a-guide-to-flexbox/
  */
  max-height: 306px;
  background-color: lightyellow;
}
li {
  width: 100px;
  height: 100px;
  background:
    linear-gradient(
      rgba(255,0,0,0.4),
      rgba(255,0,0,0.4)
    ),
    url(http://placekitten.com/g/100/100);
  color: white;
  text-align: center;
  font-size: 50px;
  line-height: 100px;
  font-weight: bold;
  border: 1px solid white;
  list-style-type: none;
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
</ul>

兼容性:IE10+
我会让你玩 Autoprefixer for IE10 和旧版本的浏览器,因为我受够了这个精彩规范的 3 个连续草稿 ^^

非常有用的资源:CSS Tricks flexbox
Codepen 上面的代码:http://codepen.io/anon/pen/MwJYjP

关于javascript - 根据div的最大高度排列元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30506909/

相关文章:

javascript - 通过 html 内容选择 javascript/jquery 中的元素

javascript - jQuery - 结合多个元素选择器与 :not - how

javascript - 将 POST 请求中的 ID 传递到单独的端点

javascript - 自定义 slider AS3 声音搜索

javascript - 尝试拉取数据时与 API 的差异

php - 使用 PHP 在两点之间插入字符串

asp.net - 页面文档模式

javascript - 滚动到顶部动画后不向下滚动

JavaScript DOM 代码不起作用

javascript - 无法使用 javascript 代码将 FF 中的字符串转换为日期格式