Sometimes, being the center of attention feels right. The perfect center (of your HTML).

There are a number of traditional ways of centering things on your web page, but they aren't fullproof (eg text-align, vertical-align, margin auto). Positioning can mess things up, coping with dynamic content can too.

There is one simple, CSS-only solution. It's a CSS double whammy and has never broken on me yet (and works in at least IE9+). Below is the code for putting something in the exact middle of whatever you want, but you can use it for just the X or Y axis.

If the item is set to position: fixed or absolute:  

top: 50%; left: 50%; transform: translate(-50%, -50%).

If the item is set to position: relative, use:

margin-top: 50%; margin-left: 50%; transform: translate(-50%, -50%).

Bonus: If the item is fixed and you want it dead center in the viewport:

top: 50vh; left: 50vw; transform: translate(-50%, -50%).

What's going on here? The top and left values move the top-left corner of the element 50% down the container and to the right. In other words, the top-left corner is in the exact middle, but the element is then too far down and to the right. The transform rule moves the element up and left half of the height and width of the element itself.

So your top/left rules are based on the parent, while the transform is based on the size of the element itself. Elegant and simple.

Still think this is a hack? Well, it is. Perfection exists though: Flexbox and CSS grid. Neither of these will ever be supported properly in IE, and both require you to manage positioning using the parent too. My method above can be used on a per element basis.