Convert width from percent to pixels
I have a table inside the <div> :
<div id="fixeddiv"> <table id="fixedtable"> <tr class="firstrow"> <td class="td11"></td> <td class="td12"></td> <td class="td13"></td> </tr> <tr class="secondrow"> <td class="td21" style="width:10%"></td> <td class="td22" style="width:20%"></td> <td class="td23" style="width:70%"></td> </tr> </table> </div> CSS
#fixeddiv { overflow:auto; margin:0px; padding:0px; position: relative; text-align:left; width: 48%; } #fixedtable { background-color: White; border-spacing:0px; cursor: pointer; width: 100%; height: 100%; font-family: Calibri !important; color: Black; font-size: 14px; } .firstrow { position: absolute; margin: 0px; left: 0; top: 0; background: url(../Content/Images/header.jpg) repeat-x center top; color: White; font-weight: bold; text-align: center; } #fixedtable tr td { padding: 5px !important; border: 1px solid #FFFFFF; text-align: center; } I compute the width of td21 using $('.td21').width() and assigning the width of td11 as $('td11').width($('.td21').width()) .
The problem is that the application of the width is not the same, they change by 1px , and I could not find how this 1px difference occurs. The width of .td21 1px greater than .td11 .
Can someone help me find a solution?
<div id="div-1" style="width: 1000px;"> <div id="div-2" style="width: 10%;"></div> </div> <script language="javascript"> var percents = parseInt(document.getElementById("div-2").style.width); var parentWidth = parseInt(document.getElementById("div-1").style.width); var pixels = parentWidth*(percents/100); alert(pixels); // will print "100" </script> This happens when you use percentage + addition. Pixel is int, so it will be rounded.
In your example: 10%, 20% and 70% is the width of the container, and you need to add padding and border.
This decimal number will happen and needs to be rounded.
Example:
Your page is 900 pixels wide. Without a fill, margin or border you will have a width of 630px (70%), 160px (20%), 90px (10%).
But when you add border + padding, percentages should be calculated from 900 - (3 tds * 10px padding (left and right)) - (3 tds * 2px border (left and right)) = 864px.
With a width of 864px you will get: 604.8px (70%), 172.8px (20%), 86.4px (10%).
And here the difference is 1px.