Frontend Development 12 min read

Implementing Middle Ellipsis for Long Titles with JavaScript and CSS

This article explains how to truncate overly long title text by showing the start and end with an ellipsis in the middle, using JavaScript to measure element widths, calculate cut‑off indices, and dynamically construct the shortened string, while also covering CSS‑only alternatives.

Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Implementing Middle Ellipsis for Long Titles with JavaScript and CSS

When a title is too long, the requirement is to show the beginning and end of the text with an ellipsis in the middle, and reveal the full text on hover. This article describes a JavaScript‑based solution that measures the real width of the container and the text, calculates the cut‑off indices, and constructs the truncated string.

Implementation steps:

Get the real width of the title box (clientWidth).

Measure the actual width of the text using a Range object.

Calculate the width occupied by each character based on font size.

Determine whether the text exceeds the container width.

Accumulate character widths to find the index where truncation should occur.

Repeat the process for the reversed text to obtain the right‑hand part.

Key code snippets:

<div class="title" id="test">近日,银行纷纷下调大额存单利率,但银行定期存款仍被疯抢。银行理财经理表示:有意向购买定期存款要尽快,不确定利率是否会再降。</div>
.title {
    width: 640px;
    height: 40px;
    line-height: 40px;
    font-size: 14px;
    color: #00b388;
    border: 1px solid #ddd;
    overflow: hidden;
    white-space: nowrap;
    padding: 0 10px;
}
// Get padding values
function getPadding(el) {
    const domCss = window.getComputedStyle(el, null);
    const pl = Number.parseInt(domCss.paddingLeft, 10) || 0;
    const pr = Number.parseInt(domCss.paddingRight, 10) || 0;
    return { left: pl, right: pr };
}

// Check if text overflows
function checkLength(dom) {
    const range = document.createRange();
    range.setStart(dom, 0);
    range.setEnd(dom, dom.childNodes.length);
    let rangeWidth = range.getBoundingClientRect().width;
    const offsetWidth = rangeWidth - Math.floor(rangeWidth);
    if (offsetWidth < 0.001) { rangeWidth = Math.floor(rangeWidth); }
    const { left, right } = getPadding(dom);
    const paddingWidth = left + right;
    return {
        status: paddingWidth + rangeWidth > dom.clientWidth,
        width: dom.clientWidth - paddingWidth
    };
}

// Calculate truncation index
function calcTextLength(text, width) {
    let realLength = 0, index = 0;
    for (let i = 0; i < text.length; i++) {
        const charCode = text.charCodeAt(i);
        realLength += (charCode >= 0 && charCode <= 128) ? 1 : 2 * 14;
        if (realLength >= width) { index = i; break; }
    }
    return index;
}

// Set truncated text
function setTextContent(text) {
    const { status, width } = checkLength(dom);
    let str = '';
    if (status) {
        const leftIdx = calcTextLength(text, width);
        const rev = text.split('').reverse().join('');
        const rightIdx = calcTextLength(rev, width);
        const rightPart = rev.substring(0, rightIdx).split('').reverse().join('');
        str = `${text.substring(0, leftIdx)}...${rightPart}`;
    } else {
        str = text;
    }
    dom.innerHTML = str;
}

Additional methods such as creating a hidden div to measure width, using canvas.measureText , and CSS‑only tricks with text-overflow: ellipsis and direction: rtl are also discussed.

The final result shows a title where the middle part is replaced by an ellipsis, and the full text appears on hover.

frontendJavaScriptCSShtmlEllipsistext-overflow
Rare Earth Juejin Tech Community
Written by

Rare Earth Juejin Tech Community

Juejin, a tech community that helps developers grow.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.