svg image

Putting your foot down - Using CSS CALC() to correctly hold the bottom of the page

There are a few issues which are common to all projects and do not have an immediately obvious, satisfactory answer - for example, the words "vertical centering" should be enough to have most web developers rolling their eyes.

 

One problem which we have encountered on a couple of projects is how to create a footer which; shows at the bottom of all pages, regardless of content height, which is not sticky and therefore only visible at the bottom of the page, below any content.

 

There are some solutions available like the wrapper/push idea but this has its drawbacks. It can be thrown off by padding and margin changes, and I personally found it was not a satisfactory way of doing this.

 

The problem stems from having to set a min-height on the content on the page. You can only do this once you know the screen height, and that usually means using JavaScript. However there is something that you can use to get round this, and it is a native CSS solution - calc().

 

calc() is still not well used by developers. It is essentially a way of calculating values at compile time in the browser to use as CSS parameters.

 

"So? I can *easily* do arithmetic in LESS and Sass!" I hear you cry. The important advantage calc() gives you is that you can perform operations on values of different units. So in our footer example, you can use a value which is full screen height (100%) minus footer height (100px) to ensure the min-height of your content.

 

min-width: calc(100% - 100px);

 

If you are using LESS you can add this to your LESS files as ~'calc(100% - 100px)' to ensure it is interpreted as a function to be carried out at compile time.

 

Another really useful application of calc() was to add a SVG shadow to removable DOM elements - by using the ::after pseudo-element and this calc() function we could add the shadow to the bottom of the element and also ensure it was always centered, ideal for responsive work where the width of elements changed at different resolutions.

 

Browser support for calc() is growing and works well in most modern browsers. There are a number of tutorials giving many more use cases. Try it in your projects!

Calculator
21st September 2017
Dash line

More Technical

Who's the driver?
Daniel

Daniel

Developer
Beginner's not-a-guide to Laravel - 4 things that will save you time
Paul

Paul

Developer
Store and share business documents securely
Yong

Yong

Developer