我正在尝试以菱形形式布置无序列表。
如果不添加 hacky <div>
,我不知道该怎么做到处都是。
我宁愿让它在语义上保持干净 ul
.
代码示例(我可以添加 id
的,没问题。)
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
<li>item 4</li>
</ul>
我希望它看起来像这样:
也许这样的事情可以用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
注意事项:
- 将容器设置为
column wrap
。 - 为了让 flex 元素知道在哪里包装,必须在容器上定义高度。
- 删除
ul
默认填充。 - 使列表项占用所有列空间。
- 中心跨越垂直和水平。
- 使第二个和第三个列表项占用一半的列空间,因此它们都适合一列。
- 将文本垂直和水平居中。
关于html - 使用 CSS 的菱形布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41230649/