CSS Scale Text to Fit Container
Learn how to automatically scale text to fit inside a container using pure CSS techniques, ensuring your designs stay responsive and elegant.
Responsive Text
Why this works
By using the clamp()
function in CSS, the font size adapts fluidly between a minimum and maximum value based on the viewport width, ensuring the text always fits nicely within the container.
Source Code
<div class="scale-text-container">
<h1 class="scale-text">Responsive Text</h1>
</div>
<style>
.scale-text-container {
width: 100%;
max-width: 600px;
height: 200px;
margin: 0 auto;
display: flex;
justify-content: center;
align-items: center;
background: #f8f9fa;
border: 2px dashed #ced4da;
border-radius: 8px;
overflow: hidden;
}
.scale-text {
font-size: clamp(1rem, 10vw, 4rem);
text-align: center;
margin: 0;
line-height: 1.2;
word-break: break-word;
}
</style>