如何按比例调整字体大小以适应div大小?

6
我正在尝试创建一个网站,在这个网站上,页面可以根据窗口大小自动调整大小。虽然我们可以通过将图片等元素的大小设置为div大小的百分比来实现自动调整大小,但我们似乎无法将div中的文本大小设置为容器的相对百分比。
该功能需要在浏览器窗口被调整大小时工作,而无需刷新页面。
该网站基于js、css、html进行开发。最简单的方法是最好的,但任何解决方案都是很棒的。
谢谢!

请问您能否发布您的代码,这样我就可以尝试为您解决问题了吗? - Michael Rader
4个回答

2

编写了一些示例来调整 div 大小变化时的字体大小。在父 div 中使用百分比并在那里调整字体大小应该可以解决问题。

http://jsfiddle.net/744A2/

$(document).ready(function() {
  $('#bigger').click(function() {
    $('#test').css('height', $('#test').height() + 100 + 'px');
    $('#test').css('width', $('#test').width() + 100 + 'px');
    check_resize();
  });
  $('#smaller').click(function() {
    $('#test').css('height', $('#test').height() - 100 + 'px');
    $('#test').css('width', $('#test').width() - 100 + 'px');
    check_resize();
  });

});

function check_resize() {
  var h = 50;
  var w = 200;

  var width = $('#test').width();
  var perc = percentage(width, w);

  $('#test').css('font-size', perc + '%');
}

function percentage(a, b) {
  return a / b * 100;
}
#test {
  font-size: 100%;
  background-color: red;
  color: white;
  padding: 20px;
  width: 200px;
  height: 50px;
}

#test h1,
#test p {
  font-size: 1em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<div id="test">
  <h1>Header</h1>
  <p>Hello World!</p>
</div>
<input type="button" value="smaller" id="smaller" />
<input type="button" value="bigger" id="bigger" />


2
所以,您可以使用screen.availHeight来计算一个常量值,然后将其乘以字体大小。
window.onload = function () {
    document.body.style.fontSize = (Math.ceil(screen.availHeight * parseInt(document.body.style.fontSize) / 600) + 'px';
}

1

使用媒体查询怎么样?


0

不幸的是,这并不起作用,因为使用font-size会将其设置为“将字体大小设置为父元素字体大小的百分比”。我需要它是父元素本身的百分比。但我感谢您的建议。 - user1116779
如果您在div宽度中使用%,则它会自动调整文本。 - Deept Raghav

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接