Using calculations in bounds properties

Ever try to center a button on a form? Dead center, from top to bottom, from right to left, no matter how the size of the form changes?

You can’t put a number like 100 into the left or top property. It won’t respond to different screen sizes.

You can’t put a percentage (like 50%): it will align the top or left of the button at 50%, not the center of the button.

There’s a handy calc() function you can use instead.

Put the following into your left and top properties:

left: calc(50% - 100px/2)
top: calc(50% - 40px/2)

The 50% gets us the middle of the form, no matter what its current size. The button is 100px by 40px. We divide those values by 2 to put half the control to the left or top of the middle.

Here’s how it looks:

Screen Shot 2015-10-27 at 4.12.24 PM

Here are a few notes about its usage:

  • You can use the 4 basic operators: +, -, *, /.
  • Spaces are required on both sides of the operators.
  • This is only at Design Time, not Runtime. You can use it in Project Properties, but not in your code.
  • You can mix %, px and other measurement types.
  • You can use this in any css field which needs a size, such as borders, margins, font sizes, etc.
  • You cannot use any variables: just actual sizes.

Bonus Feature: min() and max()

If you like calc(), you’ll love the min() and max() functions. They accept two or more comma-separated values and return the minimum or maximum accordingly, e.g.

width: max(50%, 100px)
height: min(10%, 20px)

This sets the width to half the screen width, or 100px, whichever is more.
It sets the height to be 10% of the screen size, but not less than 20 pixels.

This can prevent an element from getting too big (or too small) if the screen size changes.

This entry was posted in css, tips. Bookmark the permalink.