Although this is an old question and already has several answers (mostly based on changing the font size until the content fits), I recently had to do something similar with one of our projects.
Initially I used an edited version of Joe's answer (https://stackoverflow.com/a/33492161/587526), but then I began to think about it and realised that the same effect can be obtained much more easily by using a simple "transform: scale(x)" operation. An added advantage is that the content is scaled to exactly fit in the container, whereas adjusting font-size may result in suboptimal text sizes.
Calculating the value of the scale factor is ridiculously simple, just divide the parent container width by the child container width. If the child content is larger than the parent, the resulting value will be < 1.0 - and passing this to "transform: scale()" results in a perfectly redimensioned child element.
Here is the function I use. It uses jQuery, but could also be easily updated to use the available DOM functions directly.
The code is mostly self-explanatory, but I will point out that the child's "display" is initially changed to "inline-block" because elements such as <p>,<span> etc. do not otherwise report their widths.
Something else to be aware of, using "transform: scale()" may affect margins. In my case I needed to ensure that the child elements were centered inside the parent container so I made use of display: flex:
.parent-container {
display: flex;
flex-direction: column;
align-items: center;
}
Hope someone finds this useful!
function resizeToFit(parent, child) {
let $parent = jQuery(parent);
let $child = jQuery(child);
// Temporarily redefine child's display so we
// can obtain the real width
let $display = $child.css('display');
$child.css('display', 'inline-block');
// Remove any existing inline transform
$child.css('transform', '');
// Calculate the scale factor
let factor = $parent.width() / $child.width();
if (factor < 1.0) {
let scale = 'scale(' + factor + ')';
$child.css({
'-webkit-transform' : scale,
'-moz-transform' : scale,
'-ms-transform' : scale,
'-o-transform' : scale,
'transform' : scale
});
}
// Restore the original display value
$child.css('display', $display);
};