Converting width from percentage to pixels

前端 未结 3 1351
-上瘾入骨i
-上瘾入骨i 2020-12-17 23:25

I have a table inside a

:

相关标签:
3条回答
  • 2020-12-17 23:45

    This happens when you use percent + padding. Pixel is int and so it will be rounded.

    In your example: 10%, 20% and 70% is the width of the container and than you need to add the padding and border.

    With this decimal numbers will occur and than need to be rounded.

    EXAMPLE:

    Your page is 900px width. Without padding, margin or border you will have widths of 630px (70%), 160px (20%), 90px (10%).

    But when you add the border + padding the percents must be calculated from 900 - (3 tds * 10px padding (left and right)) - (3 tds * 2px border(left and right)) = 864px.

    With 864px width you will get: 604,8px (70%), 172,8px (20%), 86,4px (10%).

    And this is where the 1px difference occures.

    0 讨论(0)
  • 2020-12-17 23:46
    <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>
    
    0 讨论(0)
  • 2020-12-18 00:02

    Try using .outerWidth() instead of .width()

    0 讨论(0)
提交回复
热议问题