Skip to content

Instantly share code, notes, and snippets.

@lpaulger
Created September 7, 2013 15:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lpaulger/6476560 to your computer and use it in GitHub Desktop.
Save lpaulger/6476560 to your computer and use it in GitHub Desktop.
'use strict';
angular.module('fontSize',[]).directive('adjustSizeToWidth',[function(){
var valueToAdjustFor, container, textSpan, originalFontSize;
return function(scope, elm, attr) {
originalFontSize = attr.vwOriginalFontSize;
valueToAdjustFor = attr.vwAdjustSizeToWidth;
scope.$watch(valueToAdjustFor, function(){
container = elm;
textSpan = elm.children()[0];
if(!originalFontSize){
originalFontSize = parseInt($(textSpan).css('font-size'), 10);
} else {
$(textSpan).css({"font-size": originalFontSize, "display" : 'inline'});
}
var sectionWidth = parseInt(container.css('max-width'), 10);
var spanWidth = $(textSpan).width();
var newFontSize = (sectionWidth/spanWidth) * originalFontSize - 0.6;
newFontSize = (newFontSize > originalFontSize) ? originalFontSize: newFontSize; // never larger than original text
$(textSpan).css({"font-size" : newFontSize, "display" : 'table-cell', "line-height" : newFontSize/1.1 + "px"});
container.css({"display": 'table'});
});
};
}]);
<ul>
<li ng-repeat="item in items" adjust-size-to-width="item.name"><span>{{item.name}}</span></li>
</ul>
li {
height: 100px;
width: 100px;
max-width: 100px;//used to determine container width
position: relative;
display: table;
}
li span {
display: table-cell;
vertical-align: bottom;
text-align: center;
font-size: 15px;//required by directive to have an initial font size
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment