CSS實現文本溢出自動截斷

 

在web前端開發中,常常要處理的一種狀況就是「文本溢出」。比較友好的處理方式是溢出的文本不顯示,在末尾加上「…」。實現方式多種多樣,能夠直接後端程序截斷,前端js截斷或者CSS實現截斷。下面介紹CSS截斷的方法。css

主要代碼有三個屬性組成,缺一不可:html

overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;


下面是chrome下的效果:前端

注意:IE6必須指定寬度。你們能夠查看在線演示效果。web

另外須要指出的是,不一樣系統的不一樣瀏覽器(主要是IE)下,「…」會顯示不一樣的效果(能夠在不一樣瀏覽器查看在線演示)。並且對於文章類的網站,顯示大量的「…」也是級差的效果,最佳的方法仍是言簡意賅的使用必定字數的副標題用於列表。chrome

 

## 爲何不起做用後端

`text-overflow:ellipsis; ` only works when the following are true:瀏覽器

1. The element's width must be constrained in px (pixels). Width in % (percentage) won't work.
2. The element must have overflow:hidden and white-space:nowrap set.網站

The reason you're having problems here is because the width of your a element isn't constrained. You do have a width setting, but because the element is set to display:inline (i.e. the default) it is ignoring it, and nothing else is constraining its width either.this

You can fix this by doing one of the following:spa

1. Set the element to `display:inline-block` or `display:block` (probably the former, but depends on your layout needs).
2. Set one of its container elements to display:block and give that element a fixed width or max-width.
3. Set the element to float:left or float:right (probably the former, but again, either should have the same effect as far as the ellipsis is concerned).

I'd suggest display:inline-block, since this will have the minimum colateral impact on your layout; it works very much like the display:inline that it's using currently as far as the layout is concerned, but feel free to experiment with the other points as well; I've tried to give as much info as possible to help you understand how these things interract together; a large part of understanding CSS is about understanding how various styles work together.

Hope that helps.

 

https://stackoverflow.com/questions/17779293/css-text-overflow-ellipsis-not-working

相關文章
相關標籤/搜索