2

To make font that always fits nicely in its container, I always use Javascript to make divs or a certain class have their font-size always equal to their width and have their inner text elements defined in terms that font-size.

Demo: http://jsfiddle.net/pjk8t5kb/

<div class="font-size-equals-width">
    <h1>Here's a headline</h1>
    <p>Here's some paragraph text</p>
</div>

.font-size-equals-width
{
    padding: 5%;
    border: 1px solid black;
}

.font-size-equals-width h1 { font-size: 0.2em; }
.font-size-equals-width p { font-size: 0.1em; }

function scaleFontSize ( ) 
{
   $('.font-size-equals-width').each(function()
   { 
       var thisContainer = $(this); 
       thisContainer.css('font-size', thisContainer.width().toString() + 'px');
   });    
}

$(window).resize(function ( ) 
{
    scaleFontSize();       
});

$(document).ready(function()
{
    scaleFontSize();   
});

My question is whether this is possible in CSS? From what I can tell, the only font-size units are %, em, pt and px, none of which are connected to container width or height. Does Bootstrap have anything for this? (I always include Bootstrap in my project but I have a feeling that I under-utilize it.)

user5124106
  • 393
  • 2
  • 3
  • 11
  • This seems like the sort of thing that ought to be achievable with [the calc() function](https://developer.mozilla.org/en-US/docs/Web/CSS/calc), but sadly I don't think it's possible with pure CSS. – Hayden Schiff Aug 13 '15 at 14:48
  • Try my answer, hope it helps! – jKIM Aug 13 '15 at 14:51

2 Answers2

4

Code Pen: http://codepen.io/anon/pen/pJBdxP

.font-size-equals-width {
  padding: 5%;
  border: 1px solid black;
  width:50%;
  margin: 0 auto;
}

.font-size-equals-width h1 {
  font-size: 2vw;
}

.font-size-equals-width p {
  font-size: 1vw;
}

Try this

Hope it helps

jKIM
  • 155
  • 7
  • 2
    To elaborate: `vw` stands for `viewport width`. See this for more info: https://css-tricks.com/viewport-sized-typography/ – Mave Aug 13 '15 at 14:52
3

Seems like you want Viewport Percentage Units: http://dev.w3.org/csswg/css-values/#viewport-relative-lengths

Previously answered here: Font scaling based on width of container

Community
  • 1
  • 1
Robotnicka
  • 554
  • 1
  • 10
  • 20