Centering a Fixed-Sized Element with CSS

Photo by Toa Heftiba on Unsplash.

Here is one way to center a fixed-width/fixed-height div at the center of its container. This could be adapted to centering text, images, etc. within their containers. Essentially, we do a bit of arithmetic to get the fixed-sized element centered using absolute positioning and margins. Note that the parent container must have a position: relative property for this to work.

div {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 400px;
  height: 300px;
  margin-top: -150px; /* 1/2 of your element height*/
  margin-left: -200px; /* 1/2 of your element width */