When it comes to making applications or websites that support a range of devices, be it the smallest screen resolution of 320*768 or large screen monitors of 2560*1440, responsive layout or fluid layout is the first thing that comes to developers’ minds.
Fluid typography gives immense scope to re-define reading experiences on the web. However, it does introduce problems of uncontrollable scaling of font sizes and issues of potential accessibility. To achieve fluid typography layouts, media queries come to the rescue.
/* Smartphones (portrait and landscape) ———– */@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {/* Styles */}
/* iPads (landscape) ———– */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {
/* Styles */
}
/* Desktops and laptops ———– */@media only screen and (min-width : 1224px) {/* Styles */}
/* Large screens ———– */@media only screen and (min-width : 1824px) {/* Styles */}
The Rise of CSS Clamp
Imagine developing an app for book readers, where there is a lot of text to highlight and different font sizes are to be handled for all screen sizes. We define font-sizes for all range of devices and the code becomes bulky with all the media queries. With advancements coming up, you can now define font-sizes in multiple media queries with a single line of code that can handle all screen sizes. We now have CSS property ‘clamp ()’ that takes 3 parameters- minimum value, preferred value, and maximum value.
For ex- font-size{clamp(1rem , 2vw, 5rem)}
In the given example, this property allows you to limit the font size in the range of 1rem-5rem, and it varies with the change in the viewport. It is preferred to pass the preferred value in ‘vw’ viewport-width- 1% of viewport width- so that the font scales in line with the viewport without passing any mathematical logic to have the same behavior.
The property of clamp is mostly supported in all the latest browsers, which makes it more desirable among developers. Let us have a quick fallback to this is one giant formula which does serve the same purpose- font-size: calc([minimum size] + ([maximum size] – [minimum size]) * ((100vw – [minimum viewport width]) / ([maximum viewport width] – [minimum viewport width])));
For ex: font-size: calc (14px + (26 – 14) * ((100vw – 300px) / (1600 – 300)));
Where 14px – Minimum font size
26px – Maximum font size
300px – Minimum screen size
1600px – Maximum screen size