log
码中赤兔

在HTML中实现文本大小自适应

发布于 2025年1月14日
更新于 2025年1月14日
5 分钟阅读
CSS3HTML5

通过使用 CSS 的 container-type 属性,我们可以轻松实现 HTML 中的文本大小自适应效果。以下是一个具体的实现方法:

示例 HTML

<div class="auth-fit">
	<p>this is content</p>
</div>

基础 CSS 实现

div.auth-fit {
	width: 500px;
	height: 300px;
	padding: 10px;
	background-color: #f0f0f0;
	resize: both;
	overflow: auto;
	container-type: size;
}

div.auth-fit p {
	font-size: 10cqw;
}

在上述代码中,给容器添加 container-type: size; 属性后,可以根据容器的尺寸动态调整子元素的样式。10cqw 表示字体大小为容器宽度的 10%。因此,无论容器尺寸如何变化,字体大小会相应地调整。

限制字体大小范围

为了避免字体过大或过小,可以通过 clamp 函数为 font-size 添加最大值和最小值限制:

div.auth-fit p {
	font-size: clamp(10px, 10cqw, 20px);
}

上述代码中,字体大小基于容器宽度的 10%,但不会小于 10px,也不会大于 20px。


使用 container-name 实现更灵活的控制

通过 container-name 属性,我们可以为容器命名并根据条件灵活调整样式。

示例代码

div.auth-fit {
	width: 300px;
	height: 300px;
	padding: 10px;
	background-color: #f0f0f0;
	resize: both;
	overflow: auto;
	container-name: auth-fit-container; /* 为容器命名 */
	container-type: size;
}

div.auth-fit p {
	font-size: 1rem; /* 默认字体大小 */
}

@container auth-fit-container (width > 500px) {
	div.auth-fit p {
		font-size: 1.2rem; /* 当容器宽度大于 500px 时,字体大小为 1.2rem */
	}
}

@container auth-fit-container (width < 200px) {
	div.auth-fit p {
		font-size: 0.8rem; /* 当容器宽度小于 200px 时,字体大小为 0.8rem */
	}
}

代码说明

  1. 命名容器:通过 container-name 属性为容器命名为 auth-fit-container,便于在样式规则中引用。
  2. 条件样式:使用 @container 规则,根据容器宽度设置不同的字体大小。

总结

通过结合 container-typecontainer-name 属性,我们可以在 HTML 中实现灵活的文本大小自适应效果,并满足各种响应式设计需求。这种方法简单高效,非常适合现代 Web 开发。

关于

分享技术见解、经验和思考的个人博客

联系方式

  • Email: hushukang_blog@proton.me
  • GitHub

© 2025 码中赤兔. 版权所有