Math is fine, math is fine, but do you want to spend your time doing calculations when your stylesheet can do it for you?
CSS comes with three handy math functions that will change the way you design your websites. We’ll show you how and why you should use them.
Introducing Math to CSS
CSS is mostly declarative, but revisions have introduced functions into the language. There are now many functions in the spec, and three of the simplest math functions can come in very handy: calc, max, and min.
You can use this simple CodePen example to help follow along with the guide.
CSS math function calc()
The CSS calc() function performs a simple calculation and uses the result as the property value. This means you can assign dynamic values to properties like height and width, all without @media CSS queries.
This function supports addition (+), multiplication
subtraction (-) and division (/) with a single operator.
Example: Creating regular spacing on screen sizes
diagram showing spaces of different sizes in a web page
USE VIDEO OF THE DAY
width: calc(100vw - 400px);
If we use calc() instead, we can set the spacing to be the same on all screen sizes. The property we use for this looks like this:
diagram showing css calc create gaps of the same size
CSS max() math function
The CSS max() function selects the highest value from a pool to add a value to a CSS property. You can add as many potential values as you want, each separated by a comma, but only the highest one will be used.
Example: Restrict the height of the navigation bar
diagram showing navbar thickness on different devices
This can make a property value great on desktop and bad on mobile, just like the image above shows. Our navigation bar has a set height of 10vh, but this makes the bar thin on desktop devices.
height: max(10vh, 80px);
We can use the max() CSS function to solve this problem:
diagram showing navigation bars at equal heights
CSS math function min()
The min() function is like the max() function, but it chooses the lowest value from a pool to use as the property value.
Example: Setting a maximum text size
diagram showing too large text on mobile devices Using a font size: 10vh;
The property on Main Header Text in our example makes the text look good on desktop, but way too large on mobile.
font-size: min(10vh, 10vw);
To change this, you can use the CSS min() function to provide alternative sizing:
diagram showing correctly sized text
Using Math for Responsive Web Design
The math functions that come with CSS provide a unique way to easily create responsive websites. You just need to set them up correctly to get started.
Build a responsive navbar using only HTML and CSS
How to Create a Responsive Navigation Bar Using HTML and CSS
Click here to subscribe