首页 > 解决方案 > 为什么 justify-items 取消网格中的 1fr?

问题描述

让我们考虑以下 HTML 片段:

<div class="container">
  <div class="longText">Lorem Ipsum Dolor Sit Amet and so on !</div>
  <div class="otherContent">*</div>
</div>

.container最小宽度为 500 像素,并且.otherContent恰好需要 350 像素。

.longText需要显示在左边.otherContent,不能小于150px,如果文字太长需要省略号。

省略号部分很容易由著名的组合管理white-space: nowrap; overflow: hidden; text-overflow: ellipsis;

解决定位的方法有很多。让我们display: grid;grid-template-columns: minmax(150px, 1fr) 350px;..container

这很好用。

但是,如果我添加justify-items: start;.container则显示中断:当文本太长时,.longText不会减少,因此不会创建省略号(此处为 jsfiddle,减小浏览器的大小以查看左侧 div 与右侧重叠) .

.container {
  min-width: 500px;
  border: 1px #f00 solid;
  display: grid;
  grid-template-columns: minmax(150px, 1fr) 350px;

  justify-items: start;
}

.longText {
  border: 1px #00f solid;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.otherContent {
  height: 50px;
  width: 350px;
  border: 1px #0f0 solid;
}
<div class="container">
  <div class="longText">
    Lorem Ipsum Dolor Sit Amet and so on !
  </div>
  <div class="otherContent">
  *
  </div>
</div>

为什么justify-items会有这种效果?

标签: csscss-grid

解决方案


要解决此问题,只需添加max-width:100%

.container {
  min-width: 500px;
  border: 1px #f00 solid;
  display: grid;
  grid-template-columns: minmax(150px, 1fr) 350px;

  justify-items: start;
}

.longText {
  border: 1px #00f solid;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width:100%;
}

.otherContent {
  height: 50px;
  width: 350px;
  border: 1px #0f0 solid;
}
<div class="container">
  <div class="longText">
    Lorem Ipsum Dolor Sit Amet and so on !
  </div>
  <div class="otherContent">
  *
  </div>
</div>

至于为什么,这是因为默认值是stretch元素不需要widthormax-width并且会拉伸以填充所有区域。

您可以在规范中找到更多详细信息:

拉紧

使用非替换框的内联尺寸计算规则(在CSS 2 §10.3.3 块级,正常流程中的非替换元素中定义)。

所有其他值

将项目大小调整为适合内容。

因此fit-content,除非您明确定义width/max-width或使用stretch.

作为旁注,1fr在两种情况下都没有取消并且列宽相同。只有列内元素的宽度在变化。


推荐阅读