Before I knew these two CSS tricks, I was acting just like the guy that stuck carrots in his eyes.
If you knew these tricks from the beginning of your programming journey, you have passed the carrots-in-eyes phase.
Trick #1: the calc()
function
I made a navbar that was 70px tall and 100% wide. I had to use JS to size the rest of the body like this: navbar.style.height = window.innerHeight - 70px;
What if I didn't want to use JS (which I didn't)?
I banged my head in the computer once I found out about the css calc()
function. Now I could style an element as shown below:
#element{
width: calc(100% - 70px);
}
The calc()
function takes in a number of units in a mathematical expression. As far as I know, it can add, subtract, multiply, and divide. I'm not sure if it can calculate square roots or stuff like that, but it sure is useful!
Trick #2: centering with transformations.
Have you ever had trouble centering an element vertically and horizontally? Here is the best way to do it.
First, make sure you set the position of the element
#element{
position: absolute;
top: 50%;
left: 50%;
}
Now usually, the element will not be centered. Its corner should be at the center of its parent element. The next step is a simple line of code.
Add transform: translate(-50%, -50%);
in.
#element{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
The transformation will translate the element relative to its own size. If I use translate(-100%);
and the element's width is 300px
, the element will be translated -300px
in the X direction. No matter what size the element is, if you use the -50%, -50%
transformation, it will be centered for sure.
Discussion (4)
Although translate does the trick in some desperate cases when you are forced to use absolute positioning, i would recommend 99% of the time to go with css flexbox instead. The centering is much more solid and is the de facto way to center elements anyhow you desire. Its super powerful and used in every modern web layout design. Check out more about it!
Yup, was gonna say this. It's less verbose and more flexible 😁.
Centering, both horizontally and vertically, can be as simple as:
More info here
I'm not sure if it can calculate square roots or stuff like that, but it sure is useful! --> it will soon: w3.org/TR/css-values-4/#exponent-f...