One of the CSS units I use most is the wonderful % — so handy for positioning elements on the page.
Unfortunately, the rules aren’t exactly straightforward. One question I’m always asking myself is:
Percent of what?
Hopefully this guide can help clear things up.
Just give me the gist!In these examples, the purple box is our lovely self element — this is the element we’re trying to position using CSS properties. The surrounding blue box is the parent element.
Let’s start with our most basic, and most straightforward, example: width
and height
. Move the sliders around to get a feel for how the width and height of our self element changes with different percentage values.
.self {
position: absolute;
height: 50%;
width: 50%;
}
We can see that our element’s width
and height
are based on our parent’s width
and height
(respectively).
Great! Seems pretty straightforward — let’s move on to left
and top
:
.self {
position: absolute;
height: 50%;
width: 50%;
top: 0%;
left: 50%;
}
These values are also based on our parent’s width
and height
. If an element has a left
value of 50%
, its left side will sit halfway across its parent component.
What about margin
s?
.self {
position: absolute;
height: 50%;
width: 50%;
margin-top: 0%;
margin-left: 50%;
}
margin
s work similarly to our last example — they are based on the size of their parent. However, there is one weird thing here that is important to note:
margin-top
is based on our parent’s width, not height (and the same goes for margin-bottom
). In other words, all margin
s are a percent of their parent's width.
And what about padding
? Should be the same as margin
, right?
.self {
position: absolute;
height: 50%;
width: 50%;
padding-top: 0%;
padding-left: 50%;
}
And it is! For the most part.
Something interesting you might notice here is that padding-left
(for example) won’t change the width
of our self element, unless the padding-left
value is greater than our self element’s width
. This is because I use the border-box
box-sizing
model. Unfamiliar, or need a recap? Read more on MDN.
Okay! Here is where things get a bit... weird.
Let’s take a look at transform: translate
:
.self {
position: absolute;
height: 50%;
width: 50%;
translate-top: 0%;
translate-left: 50%;
transform: translate(50%, 0%);
}
The box moves a lot more slowly this time, right? That’s because transform: translate
percentage values are based on our self element’s
width
and height
.
Let’s recap what we’ve learned:
Now let’s put what we’ve learned to the test!
How could we center an element inside its parent, no matter its own dimensions?
Try centering our self element inside of the parent. Make sure it doesn’t move around when you tweak its width
and height
.
.self {
position: absolute;
height: 50%;
width: 50%;
top: 0%;
left: 50%;
translate-top: 0%;
translate-left: 50%;
transform: translate(50%, 0%);
}
See how this works? We’re moving our self element:
top: 50%
left: 50%
transform: translate (top): -50%
transform: translate (left): -50%