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 */
}
Cover photo by Toa Heftiba
The content in this post is old, some of this information might be out of date. Please confirm with official documentation.