css: centering elements easily

2021-05-04

 | 

~2 min read

 | 

323 words

When I first started writing websites, I thought of a web page as a page. That is, a piece of paper. 8.5” x 11”. But that’s not how it worked at all! The result is that I found centering content on the screen anything but straightforward!

Fortunately, there are tricks like margin: 0 auto; that do a nice job of centering elements within their parent because margin is hungry - it’ll eat up all available space! (Not that dissimilar from flex by the way.)

One way to center your content vertically as well as horizontally, however, is by using absolute positioning and using width/height to define the dimensions of the element. The key, though, is to set top,right, bottom, and left to 0.

This works by taking the element out of the document flow1 and then the directions mean that we don’t “nudge” the element in any direction (and in fact lock it). At this point, we’ve now bound it to the corners and the element will fill the whole screen. Combining the pins (top, right, bottom, left) with a height and width, and we’re able to successfully limit the element to the portion of the screen we want to dedicate, but importantly, it’s in the center of the screen, not pinned to the top left, which is where an absolutely positioned element starts.

For example, the below code would put a box in the middle of the screen that is centered and takes up 50% of the height and 50% of the width.

.box {
  position: absolute;
  top: 0px;
  left: 0px;
  right: 0px;
  bottom: 0px;
  width: 50%;
  height: 50%;
  background: deeppink;
  margin: auto;
}
<div class="box"></div>

Here’s a small CodePen further illustrating the point.

Footnotes

  • 1 This is what the absolute positioning does. If the element is a child of the <body> tag, it will be a great candidate for a modal for example.

Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!