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

为何代码中justify-content: space-between属性未生效?

问题描述

当前布局效果:
当前布局截图:一排无间距的方块

上图为仪表盘中第一个容器的当前效果,容器内的内容块紧密贴合在一起。

期望实现的效果:
布局效果图:方块间存在间距,且每个方块内的文本沿双轴居中

使用MudBlazor编写的HTML代码:

<MudContainer Class="firstRowContainer" MaxWidth="MaxWidth.Large">
    <MudGrid>
        <MudPaper Elevation="6" Class="firstRowContent">
            <p>Amount bookings today</p>
        </MudPaper>
        <MudPaper Elevation="3" Class="firstRowContent">
            <p>Amount open quotes</p>
        </MudPaper>
        <MudPaper Elevation="3" Class="firstRowContent">
            <p>top 10 customs amount bookings per range</p>
        </MudPaper>
        <MudPaper Elevation="3" Class="firstRowContent">
            <p>Amount new customers today</p>
        </MudPaper>
        <MudPaper Elevation="3" Class="firstRowContent">
            <p>top 10 ports</p>
        </MudPaper>
        <MudPaper Elevation="3" Class="firstRowContent">
            <p>Amount active bookings</p>
        </MudPaper>
    </MudGrid>
</MudContainer>

CSS代码:

<style>
    .firstRowContainer {
        position: relative;
        display: flex;
        flex: none;
        flex-direction: row;
        justify-content: space-between;
        top: 10px;
        margin-left: 5px;
        padding: 11px;
    }

    .firstRowContent {
        border: 0.5px solid aliceblue;
        flex: none;
        top: 5px;
        width: 150px;
        max-width: 150px;
        height: 80px;
    }
</style>

我尝试过用display: flex但没效果,怀疑容器和内容的父子元素关系设置不对,请问怎么给这些方块加间距?


解决方案

问题核心是flex布局的作用对象错误:你把flex属性加在了外层MudContainer上,但实际需要控制布局的是内部的MudGrid——因为MudPaper是MudGrid的直接子元素。结合文本居中需求,具体调整如下:

1. 修改CSS代码

<style>
    .firstRowContainer {
        position: relative;
        top: 10px;
        margin-left: 5px;
        padding: 11px;
    }

    /* 给MudGrid设置flex布局并添加方块间距 */
    .firstRowContainer .mud-grid {
        display: flex;
        gap: 16px; /* 可根据需求调整间距大小 */
        justify-content: flex-start; /* 可选:用space-between可让方块均匀分布 */
        flex-wrap: wrap; /* 可选:屏幕宽度不足时自动换行 */
    }

    .firstRowContent {
        border: 0.5px solid aliceblue;
        flex: none;
        top: 5px;
        width: 150px;
        max-width: 150px;
        height: 80px;
        /* 实现文本双轴居中 */
        display: flex;
        align-items: center;
        justify-content: center;
        text-align: center;
    }
</style>

2. 关键说明

  • 之前的flex设置无效,是因为MudContainer的直接子元素只有MudGrid,flex规则没有作用到MudPaper上。让MudGrid成为flex容器,才能直接控制方块的布局。
  • gap属性是最简洁的设置元素间距的方式,避免用margin引发的布局冲突。
  • 在.firstRowContent中添加flex相关属性,可让内部文本在垂直、水平方向都居中,text-align: center用于处理多行文本的对齐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 13:18:09