How work clamp in css?

How work clamp in css?

Published on Updated on

The CSS `clamp` function is a new feature that allows you to set a range of values for a CSS property, based on the size of the viewport. The clamp function has three arguments: the minimum value, the preferred value, and the maximum value, separated by commas.

Here's an example of how to use `clamp` to set the font size of a heading element:

h1 {
  font-size: clamp(2rem, 5vw, 4rem);
}

In this example, we're using `clamp` to set a range of values for the `font-size` property of the `h1` element. The minimum value is `2rem`, the preferred value is `5vw` (which means 5% of the viewport width), and the maximum value is `4rem`. This means that the font size of the heading will be responsive and adjust to different screen sizes, but will never be smaller than `2rem` or larger than 4rem.

The `clamp` function can also be used with other CSS properties, such as `line-height`, `padding`, and `margin`, to create responsive layouts that adapt to different viewport sizes.

.container {
  padding: clamp(10px, 2vw, 30px) clamp(20px, 5vw, 50px);
  margin: clamp(10px, 2vw, 30px) clamp(20px, 5vw, 50px);
  font-size: clamp(1rem, 2.5vw, 1.5rem);
  line-height: clamp(1.2, 3vw, 1.5);
}

In this example, we're using clamp to set a range of values for the `padding`, `margin`, `font-size`, and `line-height` properties of a `.container` class. The values for each property will be responsive and adapt to different viewport sizes, but will always fall within the specified range.

By using `clamp` in your CSS styles, you can create more flexible and responsive designs that adapt to different screen sizes, without having to write complex media queries.

Updated on