【问题标题】:Having a "display: inline-block" as a parent to a "display: grid" element without having text overlap?将“显示:内联块”作为“显示:网格”元素的父元素而没有文本重叠?
【发布时间】:2021-04-17 02:36:45
【问题描述】:

我正在尝试安排一组统计数据,以便:

  • 它们显示在一条水平线上
  • 封闭元素的宽度不超过包含内容所需的宽度
  • 统计数据之间应该有固定的差距

我尝试使用display: grid 来实现它。这是我的方法:

.outer {
  background-color: yellow;
  display: inline-block;
}

.stats {
  display: grid;
  grid-gap: 20px;
  grid-template-columns: repeat(auto-fit, minmax(0, 1fr));
}
<div class="outer">
  <div class="stats">
    <div class="stat">
      <strong>Value:</strong> 1,234,568
    </div>
    <div class="stat">
      <strong>Another value:</strong> 98,765
    </div>
    <div class="stat">
      <strong>Test value:</strong> 83,263
    </div>
  </div>
</div>

不幸的是,这会导致一些奇怪的重叠。尽管.outer 元素有足够的扩展空间,但统计信息被包裹在几行中,并且文本进入其他列:

如何避免这个问题?我尝试添加:

.stat {
  white-space: nowrap;
}

...但文本仍然“运行”在一起。我错过了什么?

【问题讨论】:

    标签: css css-grid word-wrap


    【解决方案1】:

    主要问题源于此声明:

    grid-template-columns: repeat(auto-fit, minmax(0, 1fr))
    

    您正在将列设置为缩小到零宽度。

    另外,1fr 在这里什么也不做,因为容器中没有可用空间。 (您将主容器设置为inline-block,即最小宽度。这意味着没有额外的空间。)

    至少,这些命令似乎会混淆inline-block 算法。

    考虑将列保留为auto 宽度(默认设置)。

    并且,也许,将它们设置为出现在第一行。 (我使用了grid-auto-flow: column 技术。)

    .outer {
      background-color: yellow;
      display: inline-block;
    }
    
    .stats {
      display: grid;
      grid-gap: 20px;
      grid-auto-flow: column;
    }
    <div class="outer">
      <div class="stats">
        <div class="stat">
          <strong>Value:</strong> 1,234,568
        </div>
        <div class="stat">
          <strong>Another value:</strong> 98,765
        </div>
        <div class="stat">
          <strong>Test value:</strong> 83,263
        </div>
      </div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-08
      • 1970-01-01
      • 2018-06-10
      相关资源
      最近更新 更多