Learn to use min (), max (), clamp () in CSS and their usage scenarios

Time:2021-1-26

Author: Ahmad shaded
Translator: Xiaozhi
Source: Sitepoint

Like again, wechat searchGreat migration to the worldPay attention to this person who does not have a big factory background, but has an upward positive attitude. this paperGitHub https://github.com/qq44924588…It has been included in the book, the articles have been classified, and a lot of my documents and tutorial materials have been sorted out.

Everyone said that there was no project in the resume, so I found a project for you with a gift[building tutorial]

April 8, 2020FirefoxThe browser supports CSSComparison functionmin()max()clamp())This means that all major browsers now support them. The most important role of these CSS functions is to provide us with dynamic layout and more flexible component design methods.

These simple elements are mainly used to set element size, such as container size, font size, inner margin, outer margin, etc. In this article, I will use some examples to discuss the use of these functions in practice, hoping to help you understand them better.

compatibility

minandmaxSupport for the project:

Learn to use min (), max (), clamp () in CSS and their usage scenarios

clamp()Support for the project:

Learn to use min (), max (), clamp () in CSS and their usage scenarios

CSS comparison function

According to CSS specification,Comparison functionIt’s about comparing multiple values and taking one of them. Let’s study the function.

Min() function

min()The function supports one or more expressions separated by commas, and then takes the value of the smallest expression as the return valuemin()Sets the maximum value for the element.

Consider the following example, where we want the maximum width of the element to be500px

.element {
    width: min(50%, 500px);
}

Learn to use min (), max (), clamp () in CSS and their usage scenarios

The browser needs to(50%,500px)Take a minimum, because there is a percentage, so the final result depends on the width of the viewport. If50%The calculated value of is greater than500pxThen take500px

Otherwise, if50%The calculated value is less than500px, then50%Will be used as the value for the width, assuming the width of the viewport is900pxThe width of the final element is900px x 50% = 450px

Learn to use min (), max (), clamp () in CSS and their usage scenarios

The following is an interactive animation for better understanding:

Learn to use min (), max (), clamp () in CSS and their usage scenarios

Case source code:https://codepen.io/shadeed/debug/f5e338c8a1c7cd29e382c72a5eb37e48/auth

Max() function

max()Function summin()Function syntax is similar, the difference is thatmax()Function returns the maximum value,min()Function returns the minimum value. Again, we can useman()Sets the minimum value for the element.

Consider the following example, where we want the minimum width of the element to be500px

.element {
    width: max(50%, 500px);
}

The browser needs to(50%,500px)Take a maximum, because there is a percentage, so the final result depends on the width of the viewport. If50%The calculated value of is less than500pxThen take500px

Otherwise, if50%The calculated value is greater than500px, then50%Will be used as the value for the width, assuming the width of the viewport is1150pxThe width of the final element is1150px x 50% = 575px

Learn to use min (), max (), clamp () in CSS and their usage scenarios

Case source code:https://cdpn.io/shadeed/debug/cca927df45964fbe1a8342ad3ace6d71

Clamp() function

The clamp() function returns a range of values. The syntax is as follows:

clamp(MIN, VAL, MAX)

amongMINRepresents the minimum value,VALRepresents the preferred value,MAXRepresents the maximum value. I mean, ifVALstayMINandMAXBetween ranges, useVALAs the return value of the function; ifVALgreater thanMAX, then useMAXAs the return value; ifVALless thanMIN, then useMINAs the return value.

clamp(MIN, VAL, MAX)It’s actually equivalent tomax(MIN, min(VAL, MAX))

Consider the following example

.element {
    width: clamp(200px, 50%, 1000px);
}

Suppose we have an element whose minimum width is200px, the preferred value is50%, the maximum value is1000px, as follows:

Learn to use min (), max (), clamp () in CSS and their usage scenarios

The above calculation process is as follows:

  • The width will never be less than200px
  • The content middle preference is50%, only when the width of the viewport is greater than400pxless than2000pxIt’s only effective when it’s time
  • The width will not exceed1000px

Case source code:https://codepen.io/shadeed/pen/924419f15bfdcf0cd0103b0587524b0b?editors=0010

Context matters

The calculated value depends on the context. It could be%emremvw/vh. Even the percentage value can be based on the width of the viewport (if the element is directly in the<body>Can also be based on its parent element.

mathematical expression

It is worth mentioning that the clamp() function can also be used in mathematical expressions without the aid of thecalc(), as shown in the following code:

.type {
  /*Force font size between 12px and 100px*/
  font-size: clamp(12px, 10 * (1vw + 1vh) / 2, 100px);
}

Use cases

Sidebar and main interface

Learn to use min (), max (), clamp () in CSS and their usage scenarios

Generally, the sidebar of the page is fixed, and the main interface is flexible. If the view is large enough, we can dynamically increase the sidebar width according to the size of the viewmax()Function to set the minimum width for it.

Consider the following example:

.wrapper {
    display: flex;
}

aside {
  flex-basis: max(30vw, 150px);
}

main {
  flex-grow: 1;
}

If the viewport is larger than500px, the minimum width of the sidebar is150px(500 * 30% = 150)。

Case source code:https://codepen.io/shadeed/pen/7f9558f31fdf60bc08c827817c10bf3a?editors=1100

Title font size

Learn to use min (), max (), clamp () in CSS and their usage scenarios

clamp()A good use case of is for headings. Suppose we want the minimum size of the title to be16px, the maximum size is50pxclamp()Function will give us a value in between.

.title {
    font-size: clamp(16px, 5vw, 50px);
}

Use hereclamp()It is very suitable because it ensures that the font size used is accessible and easy to read. If you changemin()Then you can’t control the font in a small view.

.title {
    font-size: min(3vw, 24px); /* Not recommended, bad for accessibility */
}

Learn to use min (), max (), clamp () in CSS and their usage scenarios

On the mobile side, the font size is very small. Therefore, do not use themin()Function. Of course, we can also adapt through media query, but we miss a useCSS comparison functionActual combat.

As mentioned earlier, you canmax()Nested in functionmin()To achieveclamp()The function will mimic theclamp()Function, as follows:

.title {
    font-size: max(16px, min(10vw, 50px));
}

Case source code:https://codepen.io/shadeed/pen/db76480260c104df00c65991df90a203?editors=1100

Everyone said that there was no project in the resume, so I found a project for you with a gift[building tutorial]

Decorative title

Learn to use min (), max (), clamp () in CSS and their usage scenarios

Notice that there is a large translucent title under the icon title. This is a decorative text, which is scaled according to the size of the window. We can use itmax()Function sumCSS viewportCell to set its minimum value.

.section-title:before {
  content: attr(data-test);
  font-size: max(13vw, 50px);
}

Source code:https://codepen.io/shadeed/pen/e0128b73de7c84cb9b98cf733a3835c4?editors=1100

Smooth gradient

When using gradients in CSS, you may need to make some adjustments to make the transition between colors smoother. Let’s look at the following gradient first:

.element {
    background: linear-gradient(135deg, #2c3e50, #2c3e50 60%, #3498db);
}

Learn to use min (), max (), clamp () in CSS and their usage scenarios

Note that the transition of movement is separated by an obvious line, which is not good. We can solve this problem by using media query

@media (max-width: 700px) {
    .element {
        background: linear-gradient(135deg, #2c3e50, #2c3e50 25%, #3498db)
    }
}

A simpler way to do this is to usemin()Function, as follows:

.element {
    background: linear-gradient(135deg, #2c3e50, #2c3e50 min(20vw, 60%), #3498db);
}

Learn to use min (), max (), clamp () in CSS and their usage scenarios

Case source code:https://codepen.io/shadeed/pen/2c4bf2ded32f66390fdef13409be4a10?editors=1100

Transparent gradient

When we need to place text on the image, we should add a gradient layer on the image to make the text more readable. Similar to the previous example, the gradient size should be different between the small view and the large view. See the figure below:

Learn to use min (), max (), clamp () in CSS and their usage scenarios

.element {
    background: linear-gradient(to top, #000 0, transparent max(20%, 20vw));
}

Case source code:https://codepen.io/shadeed/pen/babf1bfd4c85eeb1b6f9f549dd0fe602?editors=1100

Container width

Learn to use min (), max (), clamp () in CSS and their usage scenarios

If there is a container, its width should be 80% of its parent container, but not more than780pxWhat can you use? Usually, you shouldmax-width, as follows:

.container {
    max-width: 780px;
    width: 80%;
}

Used heremin() Function can also set a maximum value for an element:

.container {
    max-width: min(80%, 780px);
}

Case source code:https://codepen.io/shadeed/pen/3d8b44709b04efdd7336fe91363e3d76?editors=1100

Boundary and shadow

Learn to use min (), max (), clamp () in CSS and their usage scenarios

In some design cases, if the width and radian of the element border are large, it should be reduced as much as possible when moving. through the use ofclamp()We can make it dynamic according to the window width.

.element {
    box-shadow: 0 3px 10px 0 red;
    border: min(1vw, 10px) solid #468eef;
    border-radius: clamp(7px, 2vw, 20px);
    box-shadow: 0 3px clamp(5px, 4vw, 50px) 0 rgba(0, 0, 0, 0.2);
}

Case source code:https://codepen.io/shadeed/pen/7b5c7979e09573ca32150ebfc7f74a66?editors=1100

Grid Gap

Learn to use min (), max (), clamp () in CSS and their usage scenarios

In an interface using style layout, if we want to adjust the spacing between grids according to the size of the viewport, useclamp()It’s easy to do:

.wrapper {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  grid-gap: clamp(1rem, 2vw, 24px);
}

Case source code:https://codepen.io/shadeed/pen/a14c7d9fcbbae84340a4f83833294f5b?editors=1100

If you use these methods in an incompatible browser

As with any new CSS function, it’s important to provide a fallback scheme. To achieve this, we can use one of the following methods:

1. Manually add a fallback scheme

We can use theComparison functionAdd a default method before, as shown below:

.hero {
    padding: 4rem 1rem;
    padding: clamp(2rem, 10vmax, 10rem) 1rem;
}

Supported browsers will ignore the first one, and unsupported browsers will use the first onepadding

Using CSS@supports

We can use it@supportsCheck whether the browser supports CSS comparison function, as follows:

.hero {
    /*Default value for unsupported browsers*/
    padding: 4rem 1rem;
}

@supports (width: min(10px, 5vw)) {
   /*Browsers for support*/
  .hero {
    padding: clamp(2rem, 10vmax, 10rem) 1rem;
  }
}

It is impossible to know the bugs that may exist after the code is deployed in real time. Afterwards, in order to solve these bugs, we spent a lot of time debugging the log. By the way, we recommend an easy-to-use bug monitoring toolFundebug

Original text:https://heydesigner.com/every…

communication

The article is updated continuously every week and can be searched by wechatGreat migration to the worldThe first time to read, reply[welfare]There are many front-end videos waiting for you, GitHubhttps://github.com/qq449245884/xiaozhiIt’s included. Welcome star.

Learn to use min (), max (), clamp () in CSS and their usage scenarios

Recommended Today

How to Build a Cybersecurity Career

Original text:How to Build a Cybersecurity Career How to build the cause of network security Normative guidelines for building a successful career in the field of information security fromDaniel miesslerstayinformation safetyCreated / updated: December 17, 2019 I’ve been doing itinformation safety(now many people call it network security) it’s been about 20 years, and I’ve spent […]