You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bootstrap 4列表项单行显示(省略号无效)问题求助

解决Bootstrap 4卡片列表项单行溢出显示省略号的问题

嘿,我来帮你搞定这个单行溢出显示省略号的问题!你的代码没生效,是因为默认的list-group-item和里面的<p>标签都没有设置单行溢出的相关样式,不过Bootstrap的card已经帮我们搞定了容器宽度的约束,只要补全样式就行。

解决方案:添加自定义CSS样式

我们只需要给要实现单行省略的文本元素加上三个关键CSS属性,再调整下默认边距就可以了。下面是完整的示例代码:

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>

<style>
  /* 自定义单行省略样式类 */
  .single-line-truncate {
    white-space: nowrap;    /* 强制文本不换行 */
    overflow: hidden;       /* 隐藏超出容器的内容 */
    text-overflow: ellipsis;/* 用省略号代替隐藏内容 */
    margin-bottom: 0;       /* 去掉p标签默认的下边距,让列表项更整齐 */
  }
</style>

<!-- 带宽度约束的卡片(可以用Bootstrap网格类或直接设置宽度) -->
<div class="card" style="width: 25rem;">
  <ul class="list-group list-group-flush">
    <li class="list-group-item">
      <p class="single-line-truncate">Long content ............. Here is some super long text that should be truncated with an ellipsis when it's longer than the card's width.</p>
    </li>
    <li class="list-group-item single-line-truncate">
      直接把样式加在list-group-item上也可以,这样不用嵌套p标签:Another even longer piece of content that needs to stay in one line.
    </li>
  </ul>
</div>

关键样式说明

  • white-space: nowrap;:强制文本始终在一行显示,不会自动换行
  • overflow: hidden;:把超出容器宽度的部分隐藏起来
  • text-overflow: ellipsis;:用省略号...代替被隐藏的内容
  • margin-bottom: 0;:消除<p>标签默认的下边距,避免列表项之间出现多余的空隙

额外提示

  • 你可以通过Bootstrap的网格类(比如col-sm-6、col-md-4)来控制卡片的宽度,比直接写内联样式更符合Bootstrap的设计规范
  • 如果不需要<p>标签,直接把single-line-truncate类加到list-group-item上,效果一样,代码更简洁

内容的提问来源于stack exchange,提问作者user9644796

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:42:35