overflow - CSS 文本溢出 : ellipsis; not working?

标签 overflow ellipsis css

我不知道为什么这个简单的 CSS 不起作用...

.app a {
  height: 18px;
  width: 140px;
  padding: 0;
  overflow: hidden;
  position: relative;
  margin: 0 5px 0 5px;
  text-align: center;
  text-decoration: none;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #000;
}
<div class="app">
  <a href="">Test Test Test Test Test Test</a>
</div>

应该在第四次“测试”前后切断

最佳答案

text-overflow:ellipsis; 仅在满足以下条件时有效:

  • 元素的宽度必须限制在 px(像素)内。 % 中的宽度(百分比)将不起作用。
  • 该元素必须设置 overflow:hiddenwhite-space:nowrap

您在这里遇到问题的原因是因为您的 a 元素的 width 不受约束。您确实有一个 width 设置,但是因为该元素被设置为 display:inline(即默认值),它会忽略它,并且没有其他限制它的宽度。

您可以通过执行以下操作之一解决此问题:

  • 将元素设置为 display:inline-blockdisplay:block(可能是前者,但取决于您的布局需求)。
  • 将其中一个容器元素设置为 display:block 并为该元素指定固定的 widthmax-width
  • 将元素设置为 float:leftfloat:right(可能是前者,但同样,就省略号而言,两者都应该具有相同的效果) .

我建议使用 display:inline-block,因为这对您的布局的附带影响最小;就布局而言,它的工作方式与当前使用的 display:inline 非常相似,但您也可以随意尝试其他方面;我已尝试提供尽可能多的信息,以帮助您了解这些事物如何相互作用;理解 CSS 的很大一部分是理解各种样式如何协同工作。

这是您的代码片段,添加了 display:inline-block,以显示您的接近程度。

.app a {
  height: 18px;
  width: 140px;
  padding: 0;
  overflow: hidden;
  position: relative;
  display: inline-block;
  margin: 0 5px 0 5px;
  text-align: center;
  text-decoration: none;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #000;
}
<div class="app">
  <a href="">Test Test Test Test Test Test</a>
</div>

有用的引用:

关于overflow - CSS 文本溢出 : ellipsis; not working?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17779293/

相关文章:

html - CSS 溢出 :auto hiding absolutely positioned child elements that exceed parent size

sql-server - 查找表中值无法转换为 int 的行

Delphi:如何以请求的宽度和行数绘制一些文本,并以省略号结尾?

css - GEB 在元素之前查找并检查样式

javascript - Google 条形图不会在我的 HTML 中动态调整大小

css - 什么时候留空间,什么时候不在 CSS 中?

html - overflow-x visible 和 overflow-y hidden with elements protrusted beyond that have relative positioning

html - CSS3 : Flex display and overflow

html - 防止 CSS Flexbox 中的换行

javascript - HTML 文本溢出省略号检测