自动缩放字体大小以适合容器

问题描述 投票:0回答:2

我只记得有一个非常简洁的(新的?)CSS 表达式来表达“嘿字体,我希望你的尺寸恰好适合这个 div 容器”。

但是恐怕我不记得这个很酷的 CSS 表达式了。我非常确定(并且希望)有这样一个。有人可以帮忙吗?

css font-size
2个回答
0
投票

您应该使用 CSS 容器查询 通过 CSS 来实现它,但这在现代浏览器中是可能的。所以我在这种情况下使用 JS(Vue) 实现了它......

<template>
  <component :is="props.element" class="fit-text" :style="{ fontSize: `${props.maxFont}rem` }" ref="componentRef">
    <slot />
  </component>
</template>

<script setup lang="ts">
const componentRef = refsE<HTMLElement>();

function changeFontSize() {
  if (!componentRef.value) return;
  const isOverflow = componentRef.value.offsetWidth < componentRef.value.scrollWidth;
  if (!isOverflow) return;
  let fontSize = Number(componentRef.value.style.fontSize.replace(/rem/g, ''));
  const nextFontSize = fontSize - props.step;
  if (nextFontSize < props.minFont) {
    componentRef.value.style.fontSize = `${props.minFont}rem`;
    return;
  }
  componentRef.value.style.fontSize = `${nextFontSize}rem`;
  changeFontSize();
}

onMounted(async () => {
  await nextTick();
  changeFontSize();
});

const props = withDefaults(
  defineProps<{
    element?: string;
    maxFont?: number;
    minFont?: number;
    step?: number;
    maxWidth?: string;
  }>(),
  {
    element: 'p',
    maxFont: 3.25,
    minFont: 1,
    step: 0.5,
    maxWidth: '400px',
  },
);
</script>

<style scoped lang="scss">
.fit-text {
  max-width: v-bind(maxWidth);
  line-height: normal;
  text-wrap: nowrap;
}
</style>


-1
投票

我不知道有这样的表达方式。 但我可以在我的 codepen 上做一些广告;)你就得到了容器,大约 420px 宽,jQuery 计算字体大小,以适应容器。

我现在在火车上用手机,无法写出任何详细的答案。抱歉

// some code, bc links to codepen have to be accompanied by code
© www.soinside.com 2019 - 2024. All rights reserved.