字体大小与 Div 高度相同

时间:2021-04-28 19:25:58

标签: html css

我有一个绝对元素,我想要的是存档字体大小与 div 大小相同。所以基本上浏览器缩小的时候就会缩小。

我尝试过 1vw 但文本总是超出 div 元素。 [在此处输入图片说明][1]

我无法上传,但我会很简单地解释一下。 所以我有一个 div,div 是 = 100px 宽度和高度,我的文本总是超出 div 块,但我希望它缩小,即使它不可见 [1]:https://i.stack.imgur.com/Egjhy.png

2 个答案:

答案 0 :(得分:1)

我认为仅在 CSS 中是不可能的。
这是一种方法:

function setFontSize($el) {
  if ($el.find('span').text().trim().length == 0) {
    return;
  }
  let overflow = false;
  let fontSize = 0;
  const fontStep = 0.15;
  while(!overflow) {
    fontSize += fontStep;
    $el.find('span').css('font-size', fontSize + 'px');
    overflow = $el.find('span').height() > $el.height();
  }
  $el.find('span').css('font-size', (fontSize - fontStep) + 'px');
}

setFontSize($('div'));
$(window).resize(() => { setFontSize($('div')); });

$('#less').click(() => {
  $('div').height($('div').height() * 0.75);
  $('div').width($('div').width() * 0.90);
  setFontSize($('div'));
});

$('#more').click(() => {
  $('div').height($('div').height() * 1.4);
  $('div').width($('div').width() * 1.15);
  setFontSize($('div'));
});

$('#text').on('change keydown keydown', () => {
  $('div span').text($('#text').val());
  setFontSize($('div'));
});
div {
  border: 2px solid #000;
  height: 200px;
  width: 400px;
  display: flex;
  place-content: center;
  align-items: center;
}
div span {
  font-size: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<p>Control the size of the div</p>
<button id="less">-</button>
<button id="more">+</button>
<hr>
<p>Change text</p>
<input type="text" id="text" value="Lorem ipsum dolor sit amet">
<hr>

<div>
  <span>
    Lorem ipsum dolor sit amet
  </span>
</div>

答案 1 :(得分:0)

这取决于如何定义 div 的宽度,以确切地测试文本现在是否适合,但基本上我们会查看特定字体大小的文本,看看它是否适合正方形。如果不是,我们减小字体大小,看看文本现在是否适合。等等。

如果文本太多以至于字体大小不适合 1px 并且使 div 可滚动,则此代码段会中断。您可能希望将该字体大小限制设置为其他内容(请记住,某些浏览器不会让用户缩放超过 100%,例如)。

function shrink() {
  const thediv = document.querySelector('.thediv');
  let size = 16;//initial font size (in px), you may want to set it bigger
  thediv.style.fontSize = size + 'px';

  while (thediv.offsetHeight > window.innerWidth/10) {// divide by 10 because width set to 10vw
    if (size < 1 ) { thediv.style.overflowY = 'scroll'; break; }
    size = size - 0.1;
    thediv.style.fontSize = size + 'px';
  }
}
shrink();
window.onresize = shrink;
.thediv {
  width: 10vw;
  position: absolute;
}
<div class="thediv">Lorem ipsum and some other text here which will be shrunk to fitLorem ipsum and some other text here which will be shrunk to fitLorem ipsum and some other text here which will be shrunk to fitLorem ipsum and some other text here which will be shrunk to fit</div>