XIANFESchool / FE-problem-collection

前端问题收集和知识经验总结
https://github.com/ShuyunXIANFESchool/FE-problem-collection/issues
63 stars 22 forks source link

CSS text-overflow: ellipsis 如何使用 & 文本溢出造成水平不对其的问题 #13

Open hjzheng opened 8 years ago

hjzheng commented 8 years ago

css 写法

.truncate {
  width: 250px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

当然 JS 也可以实现 (如果是 AngularJS的话 可以写一个 filter)

function shorten(text, maxLength) {
    var ret = text;
    if (ret.length > maxLength) {
        ret = ret.substr(0,maxLength-3) + "...";
    }
    return ret;
}

参考地址: https://css-tricks.com/snippets/css/truncate-string-with-ellipsis/ https://software.intel.com/en-us/html5/hub/blogs/ellipse-my-text/

mayufo commented 8 years ago

问题:文本溢出造成水平不对其的问题

经常有这样的需求,给一个定宽的div.但是里面放的内容有时候会超长,这时候就有需求,要求剩下的省略号显示啊!

这个很简单啊

  width: 100px;  // 这个div宽度的定值
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;

但是 会出现这样的问题

demo

竟然没有对齐!!!

解决

1 给左边上浮的div 加 vertical-align: top;

2 给右边的下沉的div 加 vertical-align: top;

原因分析

参考w3c 规范

The baseline of an ‘inline-block’ is the baseline of its last line box in the normal flow, unless it has either no in-flow line boxes or if its ‘overflow’ property has a computed value other than ‘visible’, in which case the baseline is the bottom margin edge.

大概意思说 当一个inline-block元素被设置overflow非visible属性值后,其baseline将被强制修改为元素下外边沿。

参考

Why does this inline-block element have content that is not vertically aligned