Home >Web Front-end >CSS Tutorial >How Can I Achieve Cross-Browser Compatible CSS Text Truncation with Ellipses?
Truncating Long Strings with CSS: A Browser-Specific Odyssey
While truncating text server-side based on logical width may suffice, it often results in suboptimal results due to the varying widths of individual characters. Ideally, truncation should occur in the browser, where the physical width of rendered text can be accurately determined.
Internet Explorer's text-overflow: ellipsis property precisely accomplishes this goal, but its cross-browser compatibility is limited. Firefox lacks support for this property, leaving developers searching for alternative solutions.
Justin Maxwell's Cross-Browser Approach
Justin Maxwell offers a CSS-based workaround that supports cross-browser truncation. However, it comes with the caveat of preventing text selection in Firefox.
.ellipsis { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; -o-text-overflow: ellipsis; -moz-binding: url('assets/xml/ellipsis.xml#ellipsis'); }
ellipsis.xml Contents
<?xml version="1.0"?> <bindings xmlns="http://www.mozilla.org/xbl" xmlns:xbl="http://www.mozilla.org/xbl" xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" > <binding>
Updating Node Content in Firefox
To address a limitation with Firefox's handling of this technique, the following code can be used to update node content:
function replaceEllipsis(node, content) { node.innerHTML = content; // detect gecko browser if (YAHOO.env.ua.gecko) { var pnode = node.parentNode, newNode = node.cloneNode(true); pnode.replaceChild(newNode, node); } }
With these techniques, developers can effectively truncate long strings with CSS, ensuring that dynamic content fits within fixed-width layouts while maintaining user-friendly visual cues like ellipses to indicate truncation.
The above is the detailed content of How Can I Achieve Cross-Browser Compatible CSS Text Truncation with Ellipses?. For more information, please follow other related articles on the PHP Chinese website!