log
Swift Code Chronicles

Automatic Text Size Adjustment in HTML

Published on January 14, 2025
Updated on January 14, 2025
12 min read
CSS3HTML5

By using the CSS container-type property, you can easily achieve automatic text size adjustment in HTML. Here’s how it can be implemented:

Example HTML

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

Basic CSS Implementation

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;
}

In the above code, by adding the container-type: size; property to the container, the styles of child elements can be dynamically adjusted based on the size of the container. The value 10cqw means 10% of the container’s width. As the container size changes, the font size adjusts accordingly.

Limiting Font Size Range

To prevent the font size from becoming too large or too small, you can use the clamp function to set a maximum and minimum value for font-size:

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

In this example, the font size is based on 10% of the container’s width but is limited to a minimum of 10px and a maximum of 20px.


Flexible Control with container-name

The container-name property allows you to assign a name to a container, enabling more flexible style adjustments based on conditions.

Code Example

div.auth-fit {
	width: 300px;
	height: 300px;
	padding: 10px;
	background-color: #f0f0f0;
	resize: both;
	overflow: auto;
	container-name: auth-fit-container; /* Assign a name to the container */
	container-type: size;
}

div.auth-fit p {
	font-size: 1rem; /* Default font size */
}

@container auth-fit-container (width > 500px) {
	div.auth-fit p {
		font-size: 1.2rem; /* Font size when container width exceeds 500px */
	}
}

@container auth-fit-container (width < 200px) {
	div.auth-fit p {
		font-size: 0.8rem; /* Font size when container width is less than 200px */
	}
}

Code Explanation

  1. Naming the Container: The container-name property assigns the name auth-fit-container to the container, making it referable in style rules.
  2. Conditional Styles: The @container rule is used to set different font sizes based on the container’s width.

Conclusion

By combining the container-type and container-name properties, you can achieve flexible automatic text size adjustments in HTML, meeting various responsive design needs. This method is simple, efficient, and well-suited for modern web development.

About

A personal blog sharing technical insights, experiences and thoughts

Quick Links

Contact

  • Email: hushukang_blog@proton.me
  • GitHub

© 2025 Swift Code Chronicles. All rights reserved