html - 使用 CSS 的菱形布局

标签 html css flexbox

我正在尝试以菱形形式布置无序列表。

如果不添加 hacky <div>,我不知道该怎么做到处都是。

我宁愿让它在语义上保持干净 ul .

代码示例(我可以添加 id 的,没问题。)

<ul>
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
    <li>item 4</li>
</ul>

我希望它看起来像这样:

enter image description here

也许这样的事情可以用display: flex来实现?也许display: table-cell ?到目前为止,我已经尝试了所有方法,但我无法弄清楚。

最佳答案

一路可以用flexbox来实现布局:

ul {
  display: flex;
  flex-direction: column;                 /* 1 */
  flex-wrap: wrap;                        /* 1 */
  height: 200px;                          /* 2 */
  list-style: none;
  padding: 0;                             /* 3 */
}

li {
  flex: 0 0 100%;                         /* 4 */
  display: flex;                      
  justify-content: center;                /* 5 */
  align-items: center;                    /* 5 */
  background-color: lightyellow;
}

li:not(:first-child):not(:last-child) {   /* 6 */
  flex-basis: 50%;
}

span {
  height: 50px;
  width: 100px;
  background-color: lightgreen;
  border: 1px solid black;
  display: flex;                         /* 7 */
  justify-content: center;               /* 7 */
  align-items: center;                   /* 7 */
}
* { box-sizing: border-box; }
/* grid lines
ul {  border: 1px dashed black; }
li {  border: 1px solid red;  }
*/
<ul>
  <li><span>item 1</span></li>
  <li><span>item 2</span></li>
  <li><span>item 3</span></li>
  <li><span>item 4</span></li>
</ul>

jsFiddle

注意事项:

  1. 将容器设置为column wrap
  2. 为了让 flex 元素知道在哪里包装,必须在容器上定义高度。
  3. 删除 ul 默认填充。
  4. 使列表项占用所有列空间。
  5. 中心跨越垂直和水平。
  6. 使第二个和第三个列表项占用一半的列空间,因此它们都适合一列。
  7. 将文本垂直和水平居中。

关于html - 使用 CSS 的菱形布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41230649/

相关文章:

html - IE 11 下 flex unset 和 flex none 的区别

jquery - 用 jQuery 速记 css?

angularjs - Angular Material chalice 弹性盒布局

html - 对齐子菜单

javascript - 如何将键盘焦点设置到列表的代表父元素

javascript - 需要在浏览器底部保留包含iFrame的div

jquery - 暂时将所有 css z-index 设置为 "none"

javascript - 尝试使用 React 中构造函数中的变量设置引导进度条的宽度

html - flex 流 : column wrap doesn't stretch the parent element's width

css - 使用 flexbox 的平行列高度问题