Daniel Moss
Daniel Moss

Reputation: 567

Why does "top: 50%; translateY(-50%);" create a lower gap than it should on certain elements within the same parent?

I have this layout for my top-bar:

Top-Menu

All the elements should be vertically centered as per the design and here's my code:

https://codepen.io/anon/pen/gXGxWz

Unfortunately, the top-bar_right-part doesn't play nicely with the class core_vertical-align (notice how the left menu works) which does only this:

position: relative;
top: 50%;
transform: perspective(1px) translateY(-50%);

And as per the codepen, here's how it looks:

Wrong Vertical align What is the issue here? Additionally, the elements from the right part don't inherit the correct height (top-bar's), where as, the left menu does.

Upvotes: 0

Views: 1099

Answers (2)

Kyle Ratliff
Kyle Ratliff

Reputation: 598

Here is the start of what is going on. The problem is that position: absolute; elements are placed according to the closest position: relative; parent.

So when you are trying to do the top: 50%; transform: translateY(-50%) it is centering the element vertically based on the size and location of the .top-bar_right-part.

I have linked to a changed pen that shows the elements (more) properly placed after adding height: 100% to line 16. This sets the height of the right floating div to 100% of the parent, which in turn aligns the position: absolute; elements within it to the same size as the whole navigation. giving you a properly vertically centered item.

The main thing to remember here, is that when you area using an absolute element, it is positioned entirely based on the nearest relative parent. So make sure the relative parent is positioned properly as well as the absolute child.

line 16-18 change: https://codepen.io/KyleCRat/pen/bYvWJz

Upvotes: 0

Sagi
Sagi

Reputation: 191

If you are ok with different and better approach, I would use flexbox to vertically center elements in the navbar. Set the parent of your elements to: -display: flex; -align-items: center; It will align all your elements vertically to the center. For more info: align-items center

Upvotes: 1

Related Questions