前端:布局(用于div中有多行元素,一行只显示四个,最左或最右要紧贴父div,最顶层和最底层也要紧贴父div)

本文详细介绍了如何使用Flexbox和CSSGrid两种方法创建一个具有两行四列的布局,包括元素间距控制和首尾元素定位。通过HTML和CSS代码展示了如何实现均匀分布和换行功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 效果

一、flex实现

html

<!DOCTYPE html>
<html>
    <head>
        <title>Flexbox Layout</title>
        <style>
        .container {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
            gap: 10px;
            border: 1px solid red;
        }

        .box {
            flex: 1 0 calc(25% - 10px);
            height: 100px;
            background-color: #ccc;
            border: 1px solid black;
        }

        .box:first-child,
        .box:last-child {
            flex-grow: 0;
        }
    </style>
    </head>
    <body>
        <div class="container">
            <div class="box"></div>
            <div class="box"></div>
            <div class="box"></div>
            <div class="box"></div>
            <div class="box"></div>
            <div class="box"></div>
            <div class="box"></div>
            <div class="box"></div>
        </div>
    </body>
</html>

上述代码使用了display: flex父级容器.container设置为Flex容器,并使用flex-wrap: wrap使子元素在容器宽度不足时换行。justify-content: space-between将子元素在主轴上均匀分布,并保持首尾子元素与父容器之间的距离。

每个子元素.box使用flex: 1 0 calc(25% - 10px)来平均占据父容器的宽度,并且通过calc()函数来减去间隙的宽度。你可以根据自己的需求调整.box元素的高度、背景颜色和边框样式。

.box:first-child.box:last-child分别选择第一个和最后一个子元素,使用flex-grow: 0来防止它们在主轴上拉伸。

通过调整容器和子元素的样式,你可以实现具有两行、四个子元素的Flexbox布局,同时满足你的要求:首尾子元素与父容器挨着,中间子元素有一定的距离,并且首层和底层以及行与行之间都有间隙。

二、grid实现

html

<!DOCTYPE html>
<html>
    <head>
        <title>CSS Grid Layout</title>
        <style>
        .container {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            grid-gap: 10px;
            border: 1px solid red;
        }

        .box {
            height: 100px;
            background-color: #ccc;
            border: 1px solid black;
        }
    </style>
    </head>
    <body>
        <div class="container">
            <div class="box"></div>
            <div class="box"></div>
            <div class="box"></div>
            <div class="box"></div>
            <div class="box"></div>
            <div class="box"></div>
            <div class="box"></div>
            <div class="box"></div>
        </div>
    </body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

25号底片~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值