Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using calc() with env(safe-area-inset)

I am wanting to use env(safe-area-inset-bottom) to add margin-bottom to an element, but only when the device is an iPhone X. However, the margin added using env(safe-area-inset-bottom) does not add enough to my liking, and I wish to add an additional 34px to the bottom margin.

    margin-bottom: calc(env(safe-area-inset-bottom) + 34px);

The styling above does add the appropriate margin, however, when the device is not an iPhone X, the margin-bottom does not go back to 0px. This is because of calc(). Any suggestions? Thanks.

like image 532
awebdev Avatar asked Dec 14 '17 00:12

awebdev


2 Answers

You can wrap the calc in a @supports query like so:

.rule {
  margin-bottom: 34px;

  @supports (margin-bottom: env(safe-area-inset-bottom)) {
    margin-bottom: calc(env(safe-area-inset-bottom) + 34px);
  }
}

If you're using sass, you can write a helper mixin like so:

@mixin supports-safe-area-insets {
  @supports (padding-top: env(safe-area-inset-top)) {
    @content;
  }
}

Which you can use like this:

.rule {
  margin-bottom: 34px;

  @include supports-safe-area-insets {
    margin-bottom: calc(env(safe-area-inset-bottom) + 34px);
  }
}
like image 101
Michael Wolthers Avatar answered Sep 22 '22 16:09

Michael Wolthers


The env css function has a 2nd fallback param. https://developer.mozilla.org/en-US/docs/Web/CSS/env

env(safe-area-inset-bottom, fallback)

So you can do:

margin-bottom: calc(env(safe-area-inset-bottom, -34px ) + 34px);
like image 25
Haim Lankry Avatar answered Sep 19 '22 16:09

Haim Lankry