100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > flex布局设置justify-content为space-between 最后一个元素无法右对齐

flex布局设置justify-content为space-between 最后一个元素无法右对齐

时间:2022-06-18 12:37:44

相关推荐

flex布局设置justify-content为space-between 最后一个元素无法右对齐

给flex盒子设置justify-content:space-between,双行排列时出现最后一个元素无法右侧对齐的情况,如下图所示。

可以看到item4和item2在右侧没有对齐,代码如下:

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title><style>*{margin: 0;padding: 0;}.box {width: 400px;background: #eee;float: left;padding: 5%;}.flex {display: flex;flex-wrap: wrap;justify-content: space-between;}.clearfix:after {content: "";display: block;height: 0;clear: both;}.item {width: 45%;height: 100px;margin-bottom:10%;background:#fff;list-style:none;text-align: center;line-height: 100px;font-size:20px;color:#333;}.item:nth-child(n+3) {margin-bottom: 0;}</style></head><body><div class="box"><ul class="flex clearfix"><li class="item">1</li><li class="item">2</li><li class="item">3</li><li class="item">4</li></ul></div></body></html>

有两种解决方法:

将.item的margin-left或者margin-right或两者同时设置为auto,这个方法部分情况下左右会出现margin值,不能真正两端撑到flex盒子边缘,如下图1;另一种方法是去掉.clearfix用于清除浮动的:after伪元素,即可实现最终想要的效果,如下图2.

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。