How can I center the ul without having it get cut off?
这是一个非常好的问题,有一些困难找到一种方式来实现这一行为.
我不相信你会发现一个纯粹的CSS解决方案,但是我们可以使用一些javascript.
基本上我创建了一个附加到窗口大小事件的脚本,它将执行以下操作:
检查我们的包装元素中有多少项目:#wrapper
>将元素数量除以3(因为我们在每列中有3个元素)来发现显示项目需要多少列
>使用以下公式为包装器元素分配一个宽度:列数*每个项目的宽度(在我们的例子中是200px)
这样做我们强制在父元素中的溢出,并且滚动条将具有正常的行为,显示每个元素.
检查以下示例:
function onResize() {
var wrapper = document.querySelector('#wrapper');
var items = wrapper.querySelectorAll('li');
var columns = Math.ceil(items.length / 3);
var width = 200 * columns;
wrapper.style.width = width > window.innerWidth ? width + 'px' : '100%';
}
onResize();
window.addEventListener('resize',onResize);
html,body {
height: 100%;
text-align: center;
}
*,*:before,*:after {
Box-sizing: border-Box;
padding: 0;
margin: 0;
}
#wrapper {
height: 100%;
display: inline-flex;
align-items: center;
justify-content: center;
background-color: aqua;
}
ul {
height: 75%;
list-style: none;
display: flex;
align-content: center;
flex-direction: column;
flex-wrap: wrap;
}
li {
flex-basis: calc(100% / 3 - 2px);
color: firebrick;
border: 1px solid firebrick;
background-color: greenYellow;
width: 200px;
display: flex;
align-items: center;
justify-content: center;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9