¿Cómo hacer que el texto largo quepa dentro de un div pequeño?

3 minutos de lectura

Tengo el div con un ancho específico, pero el texto que contiene no se descompone ni encaja en el div en consecuencia.

Esta podría ser una pregunta incorrecta. ¿Cómo hacer que encaje dentro del div?

Creo que no es posible que quepa completamente dentro, al menos se puede colocar dentro del div de acuerdo con el ancho, no con la altura.

CSS

.limit{
    width:50px;
}

HTML

<div class="limit">
    <p>fasfhfhsjdhkjhdkjhfjkhdsfjkhdfjhdfiuhadfhjdfhjadskf kjahsdjfahdfuahsdf dhsf</p>
</div>

JSFDDLE

  • .limit{ ancho: 50px; ajuste de palabra: palabra de ruptura;}

    usuario2801382

    13 de diciembre de 2013 a las 11:19


  • posible duplicado de Hacer que el contenido se ajuste al ancho del div

    – Pbk1303

    13 dic 2013 a las 11:30

avatar de usuario
Sr. alienígena

Todo lo que necesitas es word-wrap: break-word;

.limit{
    width:50px;
    word-wrap: break-word;
}
<div class="limit">
    <p>fasfhfhsjdhkjhdkjhfjkhdsfjkhdfjhdfiuhadfhjdfhjadskf kjahsdjfahdfuahsdf dhsf</p>
</div>

Manifestación

Por otro lado, si no busca romper la oración, también puede usar overflow propiedad establecida en auto o overflow-x: scroll;Manifestación

  • word-wrap ahora se llama overflow-wrap, ya que según mdn: “La propiedad era originalmente una extensión de Microsoft no estándar y sin prefijo llamada word-wrap, y fue implementada por la mayoría de los navegadores con el mismo nombre. Desde entonces, se le ha cambiado el nombre a overflow- wrap, siendo word-wrap un alias”.

    – José Álvarez

    5 sep 2021 a las 23:25


Si está buscando una manera de cambiar el tamaño de la fuente del div para que se ajuste a todo el texto sin saltos de palabra ni desplazamiento, debe usar JavaScript para detectar si el texto se desborda y ajustar el tamaño de fuente en consecuencia:

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'; 
            }
        }
    }
}

Este código es parte de una prueba que he subido a Github https://github.com/ricardobrg/fitText/

  • 3 años después y sigue siendo la mejor solución 🙂 muchas gracias

    – luuchorocha

    21 de noviembre de 2021 a las 8:21

avatar de usuario
Akhil

Modificado el límite de clase. Puede mostrar todo el texto en una sola línea.

CSS

.limit p {
    overflow-x: scroll;
    white-space: nowrap;
    width: 50px;
}

También puede usar el tamaño de fuente en unidades de ‘vw’.

.limit {
font-size : 1.3vw;
}

Modificando el valor de white-space de nowrap a normal resolvió mi problema al ajustar el texto a un div fijo.

avatar de usuario
nick allen

Puedes diseñarlo así. Es muy fácil. Mira cómo número 4 es desplazado.

#ol_list li {
    width: 380px;
    height: 80px;
    background-color: silver;
    justify-content: center;
    align-items: center;
    text-align: center;
    margin-top: 0.5cm;
    border: 2px solid purple;
    border-radius: 12%;
}

 #ol_list li span {
    display: block;
    max-width: 370px;
    max-height: 20px;
    overflow-x: auto;
    white-space: nowrap;
 }
<ol id="ol_list">
<li><span>text1</span></li>
<li><span>text2</span></li>
<li><span>text3</span></li>
<li><span>scrolled ghghghfghfjhfghghhfghhghghghfghfjhfghghhfghhfghfghfghfghfghfghfghfhhhghghghfghfjhfghghhfghhfghfghfghfghfghfghfghfhhhghghghfghfjhfghghhfghhfghfghfghfghfghfghfghfhhhghghghfghfjhfghghhfghhfghfghfghfghfghfghfghfhhhghghghfghfjhfghghhfghhfghfghfghfghfghfghfghfhhhghghghfghfjhfghghhfghhfghfghfghfghfghfghfghfhhhghghghfghfjhfghghhfghhfghfghfghfghfghfghfghfhhhghghghfghfjhfghghhfghhfghfghfghfghfghfghfghfhhhghghghfghfjhfghghhfghhfghfghfghfghfghfghfghfhhhfghfghfghfghfghfghfghfhhh</span></li>
<li><span>text5</span></li>
</ol>

¿Ha sido útil esta solución?