我想创建这个布局:
当一个项目不适合容器时,我们可以移动到下一行:
当容器比较宽的项目小时,我们可以将内容包装在多行中
使用Javascript非常简单,这是示例https://jsfiddle.net/oucxsep4/.
var choices = document.querySelectorAll('li'); var maxWidth = 0; // read for (i = 0; i < choices.length; ++i) { maxWidth = Math.max(maxWidth,choices[i].offsetWidth) }; // write for (i = 0; i < choices.length; ++i) { choices[i].style.width = maxWidth + "px"; };
ul{ margin: 0; padding: 0; list-style: none; } li{ background: red; float: left; margin: 5px; }
<ul> <li>first choice</li> <li>choice</li> <li>This is the wider choice</li> <li>other choice</li> </ul>
是否可以不使用Javascript,只使用CSS?我尝试过使用flexBox但没有成功.
解决方法
可以使用简单的css:
.list-container { display: inline-flex; flex-direction: row; justify-content: center; } .list { display: flex; flex-direction: column; } .list-item { text-transform: capitalize; background-color: rgb(200,30,40); font-size: 1.3em; text-align: left; padding: 10px; margin: 1px; display: flex; flex-direction: row; flex-wrap: wrap; justify-content: flex-start; }
<!DOCTYPE html> <div class="list-container"> <div class="list"> <div class="list-item">fresh figs</div> <div class="list-item">pine nuts</div> <div class="list-item">honey</div> <div class="list-item">balsamic vinegar</div> </div> </div> <div class="list-container"> <div class="list"> <div class="list-item">fresh figs</div> <div class="list-item">pine nuts</div> <div class="list-item">honey</div> <div class="list-item">balsamic vinegar</div> </div> </div>