Scaling tables in HTML5 using AngularJS

Over the years I have often worked on websites where content is maintained in a content management system such as Joombla or WordPress. In the CMS the author uses a full-fledged WYSIWYG editor that, among other things, allows the user to modify the layout of tables in the text. In most cases the resulting table will have a hard coded width and height. This will look great in the CMS UI and probably in the most html publications.

html table styled in the csm

However sometimes the design of the publication requires the CMS Article to be published in a fixed size element on the page, for instance floating panel to the right of the main content.


Style transform Property

With CSS3 came new ways to alter DOM elements. Using the transform syntax we can change the position and size of elements relative to their viewport.

The following example finds all table elements in the DOM and, if the table is wider than its parent, scales it down so it fits the viewport.

function resizeTables() {
  var arrTable = document.getElementsByTagName("table");
  for (index = 0; index < arrTable.length; ++index) {
   var tableRef = arrTable[index];
   if (tableRef) {
     var tableWidth = tableRef.offsetWidth;
     var parentWidth = tableRef.parentNode.offsetWidth;

     if (tableWidth && parentWidth) {
       if (tableWidth > parentWidth) {
         var scale = (parentWidth / tableWidth) = "scale(" + scale + ")"; = 0;


Angular JS Directive

The script above work fine, as long is the script is run when the page loads or the content changes. Using an AngularJS directive we can simply add this behavior to the table itself.

angular.module('tableScalingApp', [])
  .directive('scaleToFit', function () {
	  function scaleToFitLink(scope, element, attrs) {
		  var tableWidth = element[0].offsetWidth;
		  var parentWidth = element[0].parentNode.offsetWidth;

		  if (tableWidth && parentWidth) {
			  if (tableWidth > parentWidth) {
				  var scale = (parentWidth / tableWidth)
				  element[0].style.transform = "scale(" + scale + ")";

	  return {
		  restrict: 'A',
		  link: scaleToFitLink

In the HTML simply add the “scale-to-fit” attribute to the table that needs to scale.

<table id="sampleTable" scale-to-fit style="width:800px;" >


<td width="60%">

 Lorem ipsum dolor …..</

<img src=""/>


<td width="40%">

Lorem ipsum dolor …..




Here is a working sample

About Author: Kees Kleimeer

Leave a Reply