You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让含img与progress的子div在父容器中横向排列并自动换行?

子div无法横向排列并自动换行的解决方法

我尝试将包含img和progress标签的子div放置在父容器.productionList中,但无论如何设置,每个子div都会独占一行。期望效果是子div横向排列,到达容器边缘后自动换行,且每个子div内部img在上、progress在下。

当前使用的CSS代码如下:

.productionList {
    border: 1px solid white;
    width: 100%;
}

.productionList div {
    width: 40px;
}

.productionList div img {
    width: 100%;
}

.productionList div progress {
    width: 100%;
}

问题原因

子div默认是块级元素,块级元素的特性就是独占一行,会自动填充父容器的宽度,因此即使设置了固定宽度,每个子div还是会单独占满一行,无法横向排列。

解决方法

以下三种方案都能实现需求,可根据实际场景选择:

方案1:Flexbox布局(推荐,现代浏览器兼容性好)

通过给父容器设置Flex布局,实现子元素横向排列并自动换行,同时让子div内部元素垂直排布:

.productionList {
    border: 1px solid white;
    width: 100%;
    display: flex;
    flex-wrap: wrap; /* 超出容器宽度自动换行 */
    gap: 8px; /* 可选:子元素间添加间距,优化视觉效果 */
}

.productionList div {
    width: 40px;
    display: flex;
    flex-direction: column; /* 让img和progress垂直排列 */
    align-items: center; /* 可选:内部元素水平居中 */
}

.productionList div img {
    width: 100%;
}

.productionList div progress {
    width: 100%;
}

方案2:Grid布局

利用Grid的自动填充特性,实现自适应的横向排列:

.productionList {
    border: 1px solid white;
    width: 100%;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(40px, 1fr)); /* 自动生成列,每列最小40px */
    gap: 8px; /* 子元素间距 */
}

.productionList div {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.productionList div img {
    width: 100%;
}

.productionList div progress {
    width: 100%;
}

方案3:inline-block布局(兼容旧浏览器)

将子div设置为行内块元素,同时处理元素间的空白间隙:

.productionList {
    border: 1px solid white;
    width: 100%;
    font-size: 0; /* 消除inline-block元素间的空白间隙 */
}

.productionList div {
    width: 40px;
    display: inline-block;
    vertical-align: top; /* 避免子元素因高度不同错位 */
    font-size: 16px; /* 恢复字体大小,不影响内部元素 */
    margin: 0 4px 8px; /* 可选:添加间距 */
}

.productionList div img {
    width: 100%;
}

.productionList div progress {
    width: 100%;
}

内容的提问来源于stack exchange,提问作者ThatLittleDrummerBoi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 14:05:08