如何使长文本适合小div?

sun*_*sun 13 html css css3

我有一个指定宽度的div,但其中的文本没有分解并相应地适合div.

这可能是一个错误的问题.如何让它适合div?

我相信完全不能完全贴合,至少可以根据宽度而不是高度安装在div内.

CSS

.limit{
    width:50px;
}
Run Code Online (Sandbox Code Playgroud)

HTML

<div class="limit">
    <p>fasfhfhsjdhkjhdkjhfjkhdsfjkhdfjhdfiuhadfhjdfhjadskf kjahsdjfahdfuahsdf dhsf</p>
</div>
Run Code Online (Sandbox Code Playgroud)

的jsfiddle

Mr.*_*ien 27

所有你需要的是 word-wrap: break-word;

.limit{
    width:50px;
    word-wrap: break-word;
}
Run Code Online (Sandbox Code Playgroud)
<div class="limit">
    <p>fasfhfhsjdhkjhdkjhfjkhdsfjkhdfjhdfiuhadfhjdfhjadskf kjahsdjfahdfuahsdf dhsf</p>
</div>
Run Code Online (Sandbox Code Playgroud)

演示

另一方面,如果你不想破坏句子,你也可以使用overflow属性设置为autooverflow-x: scroll;- Demo


Ric*_*Web 8

如果您正在寻找一种方法来调整 div 的字体大小以适应整个文本而无需断字或滚动,则应使用 JavaScript 来检测文本是否溢出并相应地调整字体大小:

function fitText(outputSelector){
    // max font size in pixels
    const maxFontSize = 50;
    // get the DOM output element by its selector
    let outputDiv = document.getElementById(outputSelector);
    // get element's width
    let width = outputDiv.clientWidth;
    // get content's width
    let contentWidth = outputDiv.scrollWidth;
    // get fontSize
    let fontSize = parseInt(window.getComputedStyle(outputDiv, null).getPropertyValue('font-size'),10);
    // if content's width is bigger then elements width - overflow
    if (contentWidth > width){
        fontSize = Math.ceil(fontSize * width/contentWidth,10);
        fontSize =  fontSize > maxFontSize  ? fontSize = maxFontSize  : fontSize - 1;
        outputDiv.style.fontSize = fontSize+'px';   
    }else{
        // content is smaller then width... let's resize in 1 px until it fits 
        while (contentWidth === width && fontSize < maxFontSize){
            fontSize = Math.ceil(fontSize) + 1;
            fontSize = fontSize > maxFontSize  ? fontSize = maxFontSize  : fontSize;
            outputDiv.style.fontSize = fontSize+'px';   
            // update widths
            width = outputDiv.clientWidth;
            contentWidth = outputDiv.scrollWidth;
            if (contentWidth > width){
                outputDiv.style.fontSize = fontSize-1+'px'; 
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

此代码是我上传到 Github 的测试的一部分https://github.com/ricardobrg/fitText/