search
HomeWeb Front-endCSS TutorialDetailed explanation of comparison functions in CSS (example introduction)

CSS comparison functions have been supported since April 2020. I like to use these functions, but my favorite is clamp(), which is also the one I use most. In this lesson, we look at these comparison functions in detail.

Detailed explanation of comparison functions in CSS (example introduction)

Clamp(), Max(), and Min() functions

clamp() The function of Limit a value between an upper limit and a lower limit. When the value exceeds the range of the minimum and maximum values, select a value between the minimum and maximum values ​​to use. It receives three parameters: minimum value, preferred value, maximum value. [Learning video sharing: css video tutorial, web front-end]

The size and positioning of fluid

is below In the example, there is a mobile phone style with two pictures placed on it at the same time, as shown below:

Detailed explanation of comparison functions in CSS (example introduction)

When the width of the container becomes smaller, we need to reduce the size of the picture. This way it won't deform. It is generally solved using percentage units, such as width: 20%, but this method does not give us much control.

We want to have a fluid size that requires a minimum and maximum value. This is where clamp comes in.

.section-image {
  width: clamp(70px, 80px + 15%, 180px);
}

Detailed explanation of comparison functions in CSS (example introduction)

Example address: codepen.io/shadeed/pen…

Decorative elements

Sometimes, we need to add some decorative elements to the corners of the page, which need to be responsive. For example, the PC side looks like this (black dot part):

Detailed explanation of comparison functions in CSS (example introduction)

Then it looks like this on the mobile side:

Detailed explanation of comparison functions in CSS (example introduction)

In order to do this, we can use media queries:

.decorative--1 {
  left: 0;
}

.decorative--2 {
  right: 0;
}

@media (max-width: 600px) {
  .decorative--1 {
    left: -8rem;
  }

  .decorative--2 {
    right: -8rem;
  }

Although this can be done, But we can use the clamp() function, which is more concise:

  .decorative--1 {
    left: clamp(-8rem, -10.909rem + 14.55vw, 0rem);
  }

  .decorative--2 {
    right: clamp(-8rem, -10.909rem + 14.55vw, 0rem);
  }

Example address: codepen.io/shadeed/pen…

fluid height

Sometimes, the height of the main area of ​​our page needs to change according to the viewport size. In this scenario, we tend to change this situation through media queries or using viewport units.

Detailed explanation of comparison functions in CSS (example introduction)

.hero {
  min-height: 250px;
}

@media (min-width: 800px) {
  .hero {
    min-height: 500px;
  }
}

We can also mix fixed values ​​and viewport units:

.hero {
  min-height: calc(350px + 20vh);
}

@media (min-width: 2000px) {
  .hero {
    min-height: 600px;
  }
}

But we need to pay attention to the height not being too high on larger viewports. So we need to set a maximum height. Using CSS clamp(), we can set the minimum, preferred and maximum height with just one CSS statement.

.hero {
  min-height: clamp(250px, 50vmax, 500px);
}

When the screen is resized, we will see that the height will gradually change according to the viewport width. In the above example, 50vmax represents 50% of the maximum viewport size.

Detailed explanation of comparison functions in CSS (example introduction)

Example address: codepen.io/shadeed/pen…

Loading Bar

Detailed explanation of comparison functions in CSS (example introduction)

The progress bar is generally a loading process from left to right. In CSS, we can position it on the left:

.loading-thumb {
  left: 0%;
}

In order to move the progress bar To position it to the far right, we can use left: 100%, but this will cause a problem. The progress bar will run outside the container:

Detailed explanation of comparison functions in CSS (example introduction)

.loading-thumb {
  left: 100%;
}

This is normal, 100% starts from the end of the progress bar, and the progress bar itself also has its own width, So the actual width will be greater than the width of the container.

We can use calc() to subtract the width of the progress bar, so that's it, but this is not 100% effective:

.loading-thumb {
  /* 40px represents the thumb width. */
  left: calc(100% - 40px);
}

Let's take a look , how to use CSS variables and comparison functions to achieve better implementation:

.loading-thumb {
  --loading: 0%;
  --loading-thumb-width: 40px;
  position: absolute;
  top: 4px;
  left: clamp(
    0%,
    var(--loading),
    var(--loading) - var(--loading-thumb-width)
  );
  width: var(--loading-thumb-width);
  height: 16px;
}

The above steps are as follows:

  • First, we set a minimum value as 0%

  • The preferred value is the current value of the --loading CSS variable

  • 最大值代表当前的加载量减去进度条件的宽度

这里的CSS clamp()为我们提供了这个组件的三种不同的状态信息,这个方案很 nice:

Detailed explanation of comparison functions in CSS (example introduction)

不仅如此,我们还可以以相同的方式来处理不同UI

Detailed explanation of comparison functions in CSS (example introduction)

.loading-progress {
  width: clamp(10px, var(--loading), var(--loading) - 10px);
}

最小值等于圆圈宽度的一半,首选值是当前的加载百分比,最大值是当前百分比与圆圈一半的减去结果。

1Detailed explanation of comparison functions in CSS (example introduction)

事例地址:codepen.io/shadeed/pen…

动态分割器

考虑下图,我们在两个区域之间有一个行分隔符。

1Detailed explanation of comparison functions in CSS (example introduction)

在移动端上,这个分隔符应该变成水平的,如下图:

1Detailed explanation of comparison functions in CSS (example introduction)

我的解决方案是使用一个边框和flex。思路是,边框作为伪元素,以填补垂直和水平状态的可用空间:

.section {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.section:before {
  content: "";
  border: 1px solid #d3d3d3;
  align-self: stretch;
}

@media (min-width: 700px) {
  .section {
    align-items: center;
    flex-direction: row;
  }
}

我们也可以使用 clamp 而不需要媒体查询的解决方案:

.section {
  --breakpoint: 400px;
  display: flex;
  flex-wrap: wrap;
}

.section:before {
  content: "";
  border: 2px solid lightgrey;
  width: clamp(0px, (var(--breakpoint) - 100%) * 999, 100%);
}

来剖析一下上面的CSS:

  • 0px:最小值,用于垂直分隔符。它的值是 0,因为我们使用的是一个CSS边框
  • (var(--breakpoint) - 100%) * 999 是一个个切换器,根据视口宽度在 0px100% 之间切换。

1Detailed explanation of comparison functions in CSS (example introduction)

动态 border Radius

一年前,发现了一个巧妙的CSS技巧。使用CSS max()函数,根据视口宽度,将卡片的border-radius0px 切换到 8px

1Detailed explanation of comparison functions in CSS (example introduction)

.card {
  border-radius: max(
    0px,
    min(8px, calc((100vw - 4px - 100%) * 9999))
  );
}

来剖析一下上面的CSS:

  • 我们有一个 max() 函数,在 0pxmin()的计算值之间进行比较,并选择较大的值。

  • min() 函数在 8pxcalc((100vw - 4px - 100%) * 9999 的计算值之间进行比较,这会得到一个非常大的正数或负数。

  • 9999 是一个很大的数字,这样 min 的值都是 8px

间距

1Detailed explanation of comparison functions in CSS (example introduction)

有时,我们可能需要根据视口宽度来改变一个组件或一个网格的间距。有了CS函数就不一样了,我们只需要设置一次。

.wrapper {
  display: grid;  
  grid-template-columns: repeat(3, 1fr);  
  grid-gap: min(2vmax, 32px);
}

Detailed explanation of comparison functions in CSS (example introduction)

原文地址:https://isdeed.com/article/use-cases-css-comparison-functions/

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of Detailed explanation of comparison functions in CSS (example introduction). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
@keyframes CSS: The most used tricks@keyframes CSS: The most used tricksMay 08, 2025 am 12:13 AM

@keyframesispopularduetoitsversatilityandpowerincreatingsmoothCSSanimations.Keytricksinclude:1)Definingsmoothtransitionsbetweenstates,2)Animatingmultiplepropertiessimultaneously,3)Usingvendorprefixesforbrowsercompatibility,4)CombiningwithJavaScriptfo

CSS Counters: A Comprehensive Guide to Automatic NumberingCSS Counters: A Comprehensive Guide to Automatic NumberingMay 07, 2025 pm 03:45 PM

CSSCountersareusedtomanageautomaticnumberinginwebdesigns.1)Theycanbeusedfortablesofcontents,listitems,andcustomnumbering.2)Advancedusesincludenestednumberingsystems.3)Challengesincludebrowsercompatibilityandperformanceissues.4)Creativeusesinvolvecust

Modern Scroll Shadows Using Scroll-Driven AnimationsModern Scroll Shadows Using Scroll-Driven AnimationsMay 07, 2025 am 10:34 AM

Using scroll shadows, especially for mobile devices, is a subtle bit of UX that Chris has covered before. Geoff covered a newer approach that uses the animation-timeline property. Here’s yet another way.

Revisiting Image MapsRevisiting Image MapsMay 07, 2025 am 09:40 AM

Let’s run through a quick refresher. Image maps date all the way back to HTML 3.2, where, first, server-side maps and then client-side maps defined clickable regions over an image using map and area elements.

State of Devs: A Survey for Every DeveloperState of Devs: A Survey for Every DeveloperMay 07, 2025 am 09:30 AM

The State of Devs survey is now open to participation, and unlike previous surveys it covers everything except code: career, workplace, but also health, hobbies, and more. 

What is CSS Grid?What is CSS Grid?Apr 30, 2025 pm 03:21 PM

CSS Grid is a powerful tool for creating complex, responsive web layouts. It simplifies design, improves accessibility, and offers more control than older methods.

What is CSS flexbox?What is CSS flexbox?Apr 30, 2025 pm 03:20 PM

Article discusses CSS Flexbox, a layout method for efficient alignment and distribution of space in responsive designs. It explains Flexbox usage, compares it with CSS Grid, and details browser support.

How can we make our website responsive using CSS?How can we make our website responsive using CSS?Apr 30, 2025 pm 03:19 PM

The article discusses techniques for creating responsive websites using CSS, including viewport meta tags, flexible grids, fluid media, media queries, and relative units. It also covers using CSS Grid and Flexbox together and recommends CSS framework

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools