Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 18, 2021 01:03 pm GMT

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))

An example of using the clamp function to improve the responsiveness of the image size

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.

Clamp supported browsers

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

Alt Text

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

Example 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

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To