html - 在行/列中垂直堆叠元素而不是水平

标签 html css

我正在创建一个 html 页面并想切换到页面的滚动和 float 。所以在正文或 div 中我想要一个元素列表。除非触摸到 div 的末尾,否则每个元素都应位于前一个元素的下方,然后它应该位于较高的部分,依此类推。因此,如果要显示的内容太多,则应提供水平滚动条。基本上,如果你将屏幕旋转 90 度,你就会得到我想要的。

从原理上讲,这些元素应该是这样的:

1  4  7  10
2  5  8  11
3  6  9  12

我真的不知道应该从哪里开始。我不知道怎么调用它,所以很难找到它。

我想我需要把我的问题分成两部分

- ordering the items so they go in the flow like in the scheme.
- scrolling horizontally.

非常感谢关于使用什么 css 的一些指导。

最佳答案

我推荐 css columns 。查看浏览器支持 here .

Live demo (click).

<ul class="col-2">
  <li>1</li>
  <li>2</li>
  <li>3</li>

  <li>4</li>
  <li>5</li>
  <li>6</li>
</ul>

CSS:

.col-2 {
  -webkit-column-count: 2;
  -moz-column-count: 2;
  column-count: 2;
}

通常,像 Masonry、Isotope 和 Packery 这样的 javascript 库用于此行为,因为 css 列仅在较新的浏览器版本中受支持。

基于父级高度的行数,或手动设置行数

这是另一个选项,我用 javascript 填充它以使其更加动态: Live demo (click).

<!-- you can determine the row count according to this container's size -->
<!-- this element is otherwise unnecessary -->
<div class="container">

<ul class="wrap">
  <li>1</li>
  <li>2</li>
  <li>3</li>

  <li>4</li>
  <li>5</li>
  <li>6</li>

  <li>7</li>
  <li>8</li>
  <li>9</li>
</ul>

</div>

CSS:

/* raise this to increase row count! */
.container {
  height: 40px;
}

.wrap .col {
  display: inline-block;
  vertical-align: top;
}

.my-class .item {
  display: block;
}

JavaScript(为简单起见使用 jQuery):

var $wrap = $('.wrap');
var $parent = $wrap.parent();
var $items = $wrap.children();

//set row count based on parent height
var rows = getRowCount($items, $parent);

//or set it manually here
//var rows = 2;

sets = [];
while ($items.length > 0) {
  sets.push($items.splice(0, rows));
}

sets.forEach(function(set, i) {
  $set = $(set);
  $set.addClass('item');
  $setLi = $('<li class="col"></li>');
  $setList = $('<ul></ul>');
  $setList.append($set);
  $setLi.append($setList);
  $wrap.append($setLi);
});

function getRowCount() {
  var rows = Math.floor($parent.height() / $items.height());
  return (rows) ? rows : 1;
}

关于html - 在行/列中垂直堆叠元素而不是水平,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21365785/

相关文章:

html - 创建标题/内容 CSS 网格布局的更简洁方法

html - 使用堆叠的 z-index 图像进行分页

html - 背景颜色不可见

css - 有没有办法使用 CSS 定位 Firefox 3.6 及以下版本?

php - CSS 文本在左浮动中开始一个新行

html - 将内部和外部 box-shadow 应用于单个 HTML 元素

html - 带变量的 CSS3 计算

javascript - HTML 和 CSS : same height two div in div

javascript - 如何在 HTA 中获取文件的关联图标 (HTML/Javascript/VBScript)

javascript - 带有鼠标事件的梯形 div