Keep height consistent without setting a height

A good example is add-ons to form inputs. Sometimes they might be buttons and sometimes just a simple symbol in a container.

One answer might be to simply set a height on the element. This is bad for two reasons:

  1. The element might not wrap text correctly
  2. Padding and line-height can cause cross browsers issues when mixed with heights.


See the Pen Keep height consistent without setting a height by Craig Dennis (@craigmdennis) on CodePen.


(gist: file:SassMeister-input.scss)

Why not set the line-height to 1 to make the calculation easier?

When the line-height is set to one, the descenders of the type actually protrude and can get cut off if overflow: hidden; is applied. The text will also be squashed together if the element does wrap.

The mixin finds the next multiple of the baseline (4 by default) and uses that as the desired line-height.

So if you specify 13px as your font size, the mixin will use 16px as the line-height and convert it into a unit-less value.

It then takes the remaining space available from the height specified, halves it, and applies that to the top and bottom padding.

Rems and px

Not only does the mixin do the heavy lifting calculations for you but it also doesn’t care whether you use rems or px for the input values. You can also specify whether you want either to be the output (rems are default).

SASS precision

There is only an issue with SASS’ decimal point precision.

By default SASS uses 5 decimal points but when using values that don’t divide easily by each other you can end up with a recurring number.

The precision needs to be at least 7 decimal points for browsers to correctly round to the correct pixel display.

Unfortunately CodePen doesn't support this so some values have been overridden manually

Fixing SASS precision:

Use it in your project

  • Add this to your project using bower bower install sass-height --save-dev
  • Download the project folder
  • Fork the project on GitHub