关于使用display:flex的弹性布局,结合js实现最后一行自动左对齐(跪求纯css实现的方法)

4 篇文章 0 订阅

一个考验基本功的功能,而我现在也才用了最流行的一种方法,希望看到的有思路的可以写下自己的做法,一整段代码如下:

实现思路:通过获取父元素的宽度以及子元素宽度进行一系列计算,补齐最后一行,达到justify-content:wrap的时候,依旧完美左对齐

<html>
    <head>
        <title></title>
        <style>
            .input1{
                width: 100px;
            }
            .parent{
                display: flex;
                flex-wrap: wrap;
                justify-content: space-evenly;
                width: 387px;
                border: solid 1px #000;
            }
            
            .parent div{
              width: 80px;
              height: 80px;
            }

            .child1{
              background: yellow;
            }
            .child2{
              background: rgb(234, 0, 255);
            }
            .child3{
              background: pink;
            }
            .child4{
              background: rgb(255, 187, 0);
            }
            .child5{
              background: green;
            }
            .child6{
              background: rgb(0, 195, 255);
            }
            .childBlank{
                background-color: #ffffff;
            }

        </style>
    </head>
    
    <body>
        <div class="parent">
            <div class="child1"></div>
            <div class="child2"></div>
            <div class="child3"></div>
            <div class="child4"></div>
            <div class="child5"></div>
            <div class="child6"></div>
        </div>
    </body>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <script>
        function calcChild(){
            console.log(1234568888)
            var parentWidth = $(".parent").width();
            var childWidth = $(".parent div").width();
            var sumChild = $(".parent div").length;
            console.log(parentWidth,childWidth,sumChild);

            //每行最多个数
            var maxNum = Math.floor(parentWidth/childWidth);
            console.log(maxNum);
            //最后一行缺多少个
            if(sumChild > 0){
                var needAddNum = (sumChild%maxNum);
                console.log(needAddNum);
                for(var i = 0;i<needAddNum;i++){
                    $(".parent").append("<div class='childBlank'></div>");
                }
                
            }
        }
        calcChild()
    </script>
</html>

复制代码就能看效果了,可是代码并没有实现监控父元素宽度变化,而去改变子元素的补充个数问题,大家可以自己捣鼓捣鼓。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值