2010-12-10 19 views
17

Estoy tratando de hacer lo que dice el título. He visto que font-size puede ser un porcentaje. Así que mi conjetura fue que font-size: 100%; lo haría, pero no.Tamaño automático de la fuente de ajuste para caber

Aquí se muestra un ejemplo: http://jsfiddle.net/xVB3t/

¿Puedo obtener un poco de ayuda por favor?

(Si es NECESARIO para hacerlo programáticamente con js no hay problema)

+2

Gracias. Aquí está para cualquiera que quiera verlo: http://jsfiddle.net/xVB3t/2/ – Diego

+1

muchas gracias por compartir el problema resuelto, que es realmente útil y es cómo deben hacerse las cosas +1! – Trufa

+0

posible duplicado de [texto dinámico de tamaño automático para llenar el contenedor de tamaño fijo] (http://stackoverflow.com/questions/687998/auto-size-dynamic-text-to-fill-fixed-size-container) –

Respuesta

13

Esta pregunta podría ayudar a salir pero yo le avise aunque esto lo resuelve a través de jQuery:

Auto-size dynamic text to fill fixed size container

Buena suerte .

La OP de esa pregunta hizo un plugin, here is the link to it (& download)

Por cierto que estoy sugiriendo jQuery porque como Gaby pointed out esto no puede hacerse, aunque CSS solamente y usted dijo que estabas dispuesto a usar js. ..

+0

Hice un resumen de esa respuesta en realidad aquí: http://stackoverflow.com/questions/4371003/dynamically-resize-text-to-fill-div/4371117#4371117 – Trufa

5

no se puede hacer con CSS.

100% es en relación con el font-size calculado del elemento principal.

referencia: http://www.w3.org/TR/CSS2/fonts.html#font-size-props

Para un look solución de jQuery en Auto-size dynamic text to fill fixed size container

+0

Gracias @Gaby, ahora entiendo el 'font-size' con porcentaje :). Pero aún estoy buscando una respuesta. – Diego

+0

@Diego, respuesta actualizada con un enlace a otra respuesta en SO. @Akinator lo publicó también. –

+0

tan simple, y estaba perdido en las soluciones de JavaScript. Plain css resolvió esto. gracias. –

0

aquí tengo una solución mootools:

Element.implement("fitText", function() { 
       var e = this.getParent(); 
       var maxWidth = e.getSize().x; 
       var maxHeight = e.getSize().y; 
       console.log(maxWidth); 
       var sizeX = this.getSize().x; 
       var sizeY = this.getSize().y; 
       if (sizeY <= maxHeight && sizeX <= maxWidth) 
        return; 

       var fontSize = this.getStyle("font-size").toInt(); 
       while((sizeX > maxWidth || sizeY > maxHeight) && fontSize > 4) { 
        fontSize -= .5; 
        this.setStyle("font-size", fontSize + "px"); 
        sizeX = this.getSize().x; 
        sizeY = this.getSize().y; 
       } 
       return this; 
      }); 

      $$("span").fitText(); 
1

un poco tarde, pero así es como me acerco a este problema:

document.body.setScaledFont = function() { 
    var f = 0.35, s = this.offsetWidth, fs = s * f; 
    this.style.fontSize = fs + '%'; 
    return this 
} 
document.body.setScaledFont(); 

La fuente del documento base ya está configurada.

Para el resto de los elementos en los tamaños de fuente del conjunto dom como% o em, se escalarán proporcionalmente.

2

Estaba buscando trabajo y me gustó la respuesta de tnt-rox, pero no pude evitar darme cuenta de que tenía algunos gastos adicionales que podrían eliminarse.

document.body.setScaledFont = function(){ 
    this.style.fontSize = (this.offsetWidth*0.35)+'%'; 
    return this; 
} 
document.body.setScaledFont(); 

Cortar la sobrecarga hace correr un poco más rápido si lo añade a un evento onresize.

Si sólo está buscando para tener la fuente dentro de un elemento específico establecido para cambiar el tamaño para adaptarse, también se puede hacer algo como lo siguiente acabo respuesta

window.onload = function(){ 
    var scaledFont = function(el){ 
      if(el.style !== undefined){ 
       el.style.fontSize = (el.offsetWidth*0.35)+'%'; 
      } 
      return el; 
     } 
     navs = document.querySelectorAll('.container>nav'), 
     i; 
    window.onresize = function(){ 
     for(i in navs){ 
      scaledFont(navs[i]); 
     } 
    }; 
    window.onresize(); 
}; 

Nicolaas notado también tenía algo extra por encima. Lo he limpiado un poco. Desde una perspectiva de rendimiento, no soy realmente un fanático de usar un ciclo while y moverme lentamente hacia abajo hasta encontrar uno que encaje.

function setPageHeaderFontSize(selector) { 
    var $ = jQuery; 
    $(selector).each(function(i, el) { 
     var text = $(el).text(); 
     if(text.length) { 
      var span = $("<span>").css({ 
        visibility: 'hidden', 
        width: '100%', 
        position: 'absolute', 
        'line-height': '300px', 
        top: 0, 
        left: 0, 
        overflow: 'visible', 
        display: 'table-cell' 
       }).text(text), 
       height = 301, 
       fontSize = 200; 
      $(el).append(span); 
      while(height > 300 && fontSize > 10) { 
       height = span.css("font-size", fontSize).height(); 
       fontSize--; 
      } 
      span.remove(); 
      $(el).css("font-size", fontSize+"px"); 
     } 
    }); 
} 
setPageHeaderFontSize("#MyDiv"); 

Y aquí es un ejemplo de mi código anterior utilizando jQuery.

$(function(){ 
    var scaledFont = function(el){ 
      if(el.style !== undefined){ 
       el.style.fontSize = (el.offsetWidth*0.35)+'%'; 
      } 
      return el; 
     }; 
    $(window).resize(function(){ 
     $('.container>nav').each(scaledFont); 
    }).resize(); 
}); 
0

Aquí hay otra solución jQuery ...

/** 
* Resizes page header font-size for the text to fit. 
* basically we add a hidden span into the header, 
* put the text into it and then keep reducing the super large font-size 
* for as long as the height of the span exceeds the super 
* tall line-height set for the test (indicating there is more than one line needed 
* to show the text). 
*/ 
function setPageHeaderFontSize(selectorString) { 
    jQuery(selectorString).each(
     function(i, el) { 
      var text = jQuery(el).text(); 
      var length = text.length; 
      if(length) { 
       var id = "TestToSeeLengthOfElement_" + i; 
       jQuery(el).append("<span style='visibility: hidden; width: 100%; position: absolute; line-height: 300px; top: 0; left: 0; overflow: visible; display: table-cell;' id='"+id+"'>"+text+"</span>"); 
       var innerEl = jQuery("#"+id); 
       var height = 301; 
       var fontSize = 200; 
       while(height > 300 && fontSize > 10) { 
        height = jQuery(innerEl).css("font-size", fontSize).height(); 
        fontSize--; 
       } 
       jQuery(innerEl).remove(); 
       jQuery(el).css("font-size", fontSize+"px"); 
      } 
     } 
    ); 
} 

//you can run it like this... using any jQuery enabled selector string (e.g. h1.pageHeaders works fine). 
setPageHeaderFontSize("#MyDiv"); 
Cuestiones relacionadas