[英]Converting width from percentage to pixels
I have a table inside a <div>
: 我在
<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: 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 am calculating the width of td21
with $('.td21').width()
and assigning the width to td11
like $('td11').width($('.td21').width())
. 我计算的宽度
td21
用$('.td21').width()
和分配宽度td11
像$('td11').width($('.td21').width())
The problem is that the widths applying are not same, they vary by 1px
and I could not find how this 1px
difference occur. 问题是应用的宽度不同,它们相差
1px
,我无法找到这个1px
差异是如何发生的。 The .td21
width is 1px
greater than .td11
. .td21
宽度比.td11
1px
。
Can any one please help me to find the 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>
尝试使用.outerWidth()而不是.width()
This happens when you use percent + padding. 使用百分比+填充时会发生这种情况。 Pixel is int and so it will be rounded.
Pixel是int,因此它将被舍入。
In your example: 10%, 20% and 70% is the width of the container and than you need to add the padding and border. 在您的示例中:10%,20%和70%是容器的宽度,而不是您需要添加填充和边框。
With this decimal numbers will occur and than need to be rounded. 使用此十进制数将发生,而不是需要舍入。
EXAMPLE: 例:
Your page is 900px width. 您的页面宽度为900像素。 Without padding, margin or border you will have widths of 630px (70%), 160px (20%), 90px (10%).
没有填充,边距或边框,您将具有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. 但是当你添加边框+填充时,百分比必须从900 - (3 tds * 10px填充(左和右)) - (3 tds * 2px边框(左和右))= 864px计算。
With 864px width you will get: 604,8px (70%), 172,8px (20%), 86,4px (10%). 宽度为864像素,您将得到:604,8px(70%),172,8px(20%),86,4px(10%)。
And this is where the 1px difference occures. 这就是发生1px差异的地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.