SASS - compare vh and px with min function

Viewed 4130

I am trying to get the minimum between 7.6% of the viewport height and 55px.

min-height: min(7.6vh, 55px);

This gives me an error about incompatible units. Can this be done?

2 Answers

The SASS compiler can't know the viewport height of the target device(s), so it is impossible to compare vh to a fixed value given pixels.

What you can do is to set the height to either of the two numbers and set a min-height to the other number. However, the semantics are slightly different, as you now also have a max-height. In the following example, the div will take (at most) 100% of the viewport height, but at least 450px:

html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

div {
  background: darkgreen;
  height: 450px;
  min-height: 100vh;
}
<div>
</div>

The Sass min() function only works when both values have the same unit (%, px, em, etc.). However, CSS itself has a min() function built in. Modern Dart Sass will automatically use the CSS function when possible.

For older versions of Sass, to use the CSS function you need to override min() with your own custom function like this:

// Override Sass min()
@function min($numbers...) {
  @return m#{i}n(#{$numbers});
}

div {
  // This now works
  width: min(7.6vh, 55px);
}

Thanks to Jianqiu Xiao on GitHub for pointing out the "override" solution.

Related