css - 为什么 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
会有这种效果?
解决方案
要解决此问题,只需添加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
元素不需要width
ormax-width
并且会拉伸以填充所有区域。
您可以在规范中找到更多详细信息:
拉紧
使用非替换框的内联尺寸计算规则(在CSS 2 §10.3.3 块级,正常流程中的非替换元素中定义)。
所有其他值
将项目大小调整为适合内容。
因此fit-content
,除非您明确定义width
/max-width
或使用stretch
.
作为旁注,1fr
在两种情况下都没有取消并且列宽相同。只有列内元素的宽度在变化。
推荐阅读
- python - 绘制年月日与体重
- r - 匹配栅格在 foreach 循环中不起作用
- r - 在R中创建不等长列表的数据框
- python - 使用递归函数在字符串之间插入字符 - python
- node.js - 具有 createdAt 和 updatedAt 时间戳的超级账本结构链码 getState()
- angular - 如何在 Angular 应用程序中为单个路由设置 404 状态码?
- python - 多进程 - 为什么 multiprocessing.Pipe python2 比 python3 快
- telegram - 当用户点击它时,inLineKeyboardButton 在哪里响应
- django - 对自定义 Django 用户模型的任何更改都在 Admin 中完全被忽略
- kivy - 在将我的 kivymd 文件转换为 apk 时,我遇到了某种错误,我无法理解那是什么