An Interest In:
Web News this Week
- April 15, 2024
- April 14, 2024
- April 13, 2024
- April 12, 2024
- April 11, 2024
- April 10, 2024
- April 9, 2024
Improving site responsiveness with CSS clamp() function
To improve the responsiveness of your site, you don't have to use some complex event listeners using the Web API ResizeObserver, calc() function
, or CSS media queries that will substitute the required page elements depending on the browser window size.
Clamp()
is the only function specifically designed to allow almost any element to adjust its size within certain limits to fit the application window.
Syntax
clamp(MIN, VALUE, MAX)
is calculated as clamp
will return the value specified by the second argument (preferred) if it is within the minimum and maximum values. Computed values can be passed as any of the arguments.max(MIN, min(VALUE, MAX))
Units
The following units can be used for the preferred value:
- The width of the viewport in% if clamp is used in the body (or the width of the container containing the clamp).
- em is the font size in the current context.
- rem is the font size in the context of the HTML element.
- vw - 1% of the window width.
- vh - 1% of the window height.
Supported browsers
Clamp is not supported in Internet Explorer only.
Where to use
Headers font
A great use case for clamp () is in headers. Let's say you want a header with a minimum size of 16 pixels and a maximum size of 50 pixels. The clamp () function will give us an intermediate value that does not go beyond the specified limits.
.title { font-size: clamp(16px, 5vw, 50px);}
Clamp () is ideal here because it ensures that the font size used is easy to read. If you use min () to set the maximum font size, then you won't be able to control the font on small screens.
CSS Grid - Responsive Grid
Another good example is the responsive CSS grid column spacing for mobile screens. With clamp, this is pretty straightforward to implement.
.wrapper { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); grid-gap: clamp(1rem, 2vw, 24px);}
Adaptive padding for sections
Clamp () is also ideal for setting the minimum and maximum spacing between sections. This can be done with the following CSS:
.section { padding: clamp(2rem, 10vmax, 10rem) 1rem;}
Original Link: https://dev.to/b3ns44d/improving-site-responsiveness-with-css-clamp-function-3119
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To