html里面li标签水平居中,html – 当水平居中时,li被切断

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值