如何在 CSS 网格布局中将文本溢出设置为省略号?

新手上路,请多包涵

我有一个网格布局,就像下面 header 中的那个。 div 中有一个文本,其宽度为 1fr 。我希望该 div 中的文本在太长时被截断。添加 text-overflow 作为 ellpsis 不起作用。知道怎么做吗?

它必须是网格,我无法改变它。

 html,
body {
  height: 100%;
  width: 100%;
  overflow: hidden;
}

body {
  display: flex;
}

.container {
  display: flex;
  flex-direction: column;
  flex: 1;
}

content {
  flex: 1;
  background-color: red;
}

header {
  background-color: limegreen;
  display: grid;
  grid-template-columns: 0fr 1fr 0fr;
}

header div {
  border: 1px solid orange;
}

.long {
  text-overflow: ellipsis;
}
 <div class="container">
  <header>
    <div>Left</div>
    <div class="long">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
    <div>Right</div>
  </header>
  <content>
  </content>
</div>

原文由 nullDev 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

将 .long css 更改为以下

.long {
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
}

您需要添加空格和溢出的原因如下:

  1. 你需要 white-space: nowrap 告诉浏览器在文本长度超过包含块宽度时不换行, white-space 属性默认值是正常的,表示它可以换行,所以不会存在这种情况文本溢出的地方;
  2. overflow 默认值可见,当文本超出包含块时,它只是显示,所以不需要溢出文本显示,只有当你设置 overflowhidden .然后,当文本不能完全显示时,它将使用 text-overflow 属性。

原文由 Luckness 发布,翻译遵循 CC BY-SA 4.0 许可协议

  1. 使用 text-overflow: ellipsis; 时也必须使用 overflow: hidden;

  2. white-space: nowrap; 不允许文本换行。

所以,像这样改变:

 .long {
  text-overflow: ellipsis;
  overflow: hidden;/*/<------------new/*/
  white-space: nowrap;/*/<---------new/*/
}

原文由 Ehsan 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题