Friday, January 13, 2017

How to scale html elements and fonts based on the container

When we generate html we can use '%' to scale the containers based on parent element. But html elements set with pixel value will not scale correctly if parent container size is changed.

Here is an example to scale html elements correctly. Keep in mind that this is not a solution for setting layouts for different devices like desktop, mobile and tablet. The example below can be used when you want the layout to look exactly the same and scale the content size and position based on parent element's size.

We can achieve this by setting the transform property
 transform: scale(scaleWidthValue,scaleHeightValue);

To scale twice the size -
-ms-transform: scale(2,2); /* IE 9 */
transform: scale(2,2); /* Safari */
transform: scale(2,2); /* Standard syntax */

Here is the codepen link to live example -http://codepen.io/deebujacob/pen/OWXjjp

/********************* Here is the auto scaling html logic ***************/
<html>
<style>
#containerElement{
width:200px;
height:120px;
}
.outerWrapperStyle{
background-color:yellow;
width:400px;
height:225px;
padding:10px;
transform-origin:top left;
}
.innerWrapperStyle{
background-color:red;
width:200px;
height:125px;
padding:10px;
}
.contentStyle{
font-family:arial;
font-size:18px;
font-color:#333;
}
.transform{/*not used directly here*/
    transform: scale(1.5,1.5); /* Standard syntax */
}
</style>
<div id="containerElement" >
<div id="contentElement" class="outerWrapperStyle transform">
<div class="contentStyle">
Outer wrapper  content.
</div>
<div class="innerWrapperStyle">
<div class="contentStyle">
Inner Wrapper Content
</div>
</div>
</div>
</div>
<script>
var containerElement = document.getElementById("containerElement");/*get container element*/
var contentElement = document.getElementById("contentElement");/*get content element*/

var scaleWidth = containerElement.clientWidth/contentElement.clientWidth; /*find out how much to scale for width*/
var scaleHeight = containerElement.clientHeight/contentElement.clientHeight; /*find out how much to scale for height*/

contentElement.style.transform  = "scale("+scaleWidth+","+scaleHeight+")"; /*set the scale on content Element*/
</script>

</html>

No comments: