简体   繁体   English

CSS字体大小属性从Percent到Pixel,如何?

[英]CSS font-size property from Percent to Pixel, How to?

I want to convert the font-size property value from percent to pixel 我想将font-size属性值从百分比转换为像素

lets say I have this html code 让我说我有这个HTML代码

     <div style="font-size: 180%;">
              <a href="http://www.example.com"> link </a>
     </div> 

How to find the equivalent value for font-size: 180%; 如何找到font-size的等价值:180%; in pixel? 在像素?

Thanks 谢谢

There is no simple answer as font sizes in percents are relative to font size of parent block. 没有简单的答案,因为百分比中的字体大小与父块的字体大小有关。 I find it easiest to do by hand, manually adjusting the font size pixel by pixel in Firebug. 我发现手动操作最容易,在Firebug中逐个像素地手动调整字体大小。

This may be somewhat tricky to do automatically. 这可能有点难以自动完成。 Font-size percentages are done against a base value, and that base value is the parent block's font size. 字体大小百分比是根据基值完成的,该基值是父块的字体大小。 This means that font size changes are nested like this: 这意味着字体大小更改嵌套如下:

<div style="font-size: 16px;">
  This text has size 16px.
  <div style="font-size: 150%;">
    This text has size 150% * 16px = 24px.
    <div style="font-size: 150%;">
      Because this div is nested, the base value is now 24px. 
      font-size: 100% would mean 24px type.
      So the size of the text here is 150% * 24px = 36px.
    </div>
  </div>
</div>

And that means that there's almost certainly no easy solution. 意味着几乎肯定没有简单的解决方案。

If you can be absolutely sure that you don't have any places where percentages are nested (as in my example above) you can simply replace all of the percentages with the base font size multiplied by the percentage. 如果您可以完全确定没有嵌套百分比的任何位置(如上例所示),您可以使用基本字体大小乘以百分比来简单地替换所有百分比。

If you do have a lot of different pages though, you probably can't rely on that. 如果你确实有很多不同的页面,你可能不能依赖它。 In that case, you're going to have to do some HTML/CSS parsing and go through all of your pages, calculating font sizes for each and every element to get it all right. 在这种情况下,您将不得不进行一些HTML / CSS解析并遍历所有页面,计算每个元素的字体大小以使其正确。 There's not an easy solution, unfortunately. 遗憾的是,这并不是一个简单的解决方案。

I need to ask though, why do you need to do this? 我需要问一下,为什么你需要这样做? As long as you declare a base font size for the page in pixels (in the body tag), there's going to be no functional difference between percentage font sizes and absolute font sizes. 只要您为页面声明基本字体大小(在body标签中),百分比字体大小和绝对字体大小之间就没有功能差异。 If you have a font declaration like this for your body: 如果您的身体有这样的字体声明:

body {
  font: 100% font1, font2;
}

then just replace it with: 然后将其替换为:

body {
  font: 16px font1, font2;
}

And unless you have some very unusual requirements, it'll work just as well as replacing all of the font size declarations for the whole page. 除非你有一些非常不寻常的要求,否则它将替换整个页面的所有字体大小声明。

(16px is the near-universal default font size for web browsers.) (16px是Web浏览器的近乎通用的默认字体大小。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM