Why Math is Useful After All

Let’s be honest, you probably hate math. Unless you’re Will Hunting of course, but even he chose love instead of math. (“It’s not your fault”. RIP Robin Williams — probably my favourite actor of all time.) As a learning developer however, mathematics and love may just very well complement one another. (Just me?)

For the current project I am working on, I am limited to only using floats (Don’t even get me started, floats suck lol). Luckily however, I found a godly silver lining.

calc() CSS function

Exploring the calc() CSS function has been a delight when it comes to resizing. Because:

  1. It does the math for us.
  2. It allows fluidity across any layout.
  3. It does the math for us.

When dealing with pixel-value margins however, we might have to do some math.

It’s simple math, not the complicated kind

So don’t worry.

Here is an example of where you might run into a problem with your layout, where you are using percentage-based widths and pixel-value margins.

Without calc()
.suggested-post figure {
width: 25%;
margin-right: 20px;
float: left;
}

Now here is where we would have to do some math on our own to account for the margin, right? (*pun intended*). With 60px of margin in total, we would just have to divide it by 4 and use this value to subtract from our percentage width.

60px/4 = 15px

We can express this in the calc() function, using the subtraction operator.

width: calc(25% - 15px);

To remove the margin on the last figure, we would just need to add the pseudo-class, last-child.

.suggested-post figure:last-child {
margin-right: 0;
}

And, viola.

With calc()
.suggested-post figure {
width: calc(25% - 15px);
margin-right: 20px;
float: left;
}
.suggested-post figure:last-child {
margin-right: 0;
}

Easy-peasy, Lemon-squeezy

If I was not limited to using floats, I probably would have flex-box’d the hell out of this project. But in this case, calc() in addition to pseudo-classes (Shout outs to last-child!) have been very helpful.

Hence, math is indeed useful after all.

Oops, I forgot to tell you. I am currently attending HackerYou’s immersive 9-week bootcamp! It’s been pretty great so far. #BootCampLife #Cohort14