Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Set Responsive Font Size using CSS
Setting responsive font size in CSS ensures text adapts to different screen sizes automatically. The vw (viewport width) unit is the most common approach, making text scale proportionally with the browser width.
Syntax
selector {
font-size: value vw;
}
Viewport Units for Responsive Font Size
| Unit | Description |
|---|---|
vw |
1% of viewport width |
vh |
1% of viewport height |
vmin |
1% of smaller viewport dimension |
vmax |
1% of larger viewport dimension |
Example: Basic Viewport Width Font Size
The following example demonstrates responsive font sizing using the vw unit −
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
font-size: 8vw;
text-align: center;
color: #333;
}
p {
font-size: 3vw;
text-align: center;
color: #666;
}
</style>
</head>
<body>
<h1>Responsive Heading</h1>
<p>This text scales with viewport width.</p>
</body>
</html>
A centered heading and paragraph that automatically resize as you change the browser width. On wider screens, text appears larger; on narrower screens, text becomes smaller.
Example: Using CSS clamp() for Better Control
The clamp() function provides minimum, preferred, and maximum font sizes for better responsive control −
<!DOCTYPE html>
<html>
<head>
<style>
.responsive-text {
font-size: clamp(16px, 4vw, 48px);
text-align: center;
padding: 20px;
background-color: #f0f8ff;
border-radius: 8px;
}
</style>
</head>
<body>
<div class="responsive-text">
Font size: minimum 16px, scales with 4vw, maximum 48px
</div>
</body>
</html>
Text in a light blue rounded box that scales between 16px and 48px based on viewport width, ensuring readability on all devices.
Conclusion
Use vw units for basic responsive font sizing or clamp() for more controlled scaling. The clamp() approach prevents text from becoming too small on mobile or too large on desktop screens.
Advertisements
