CSS

Modern Centering

There are a million and one articles discussing this topic on the web. Most of those articles are incredibly in depth but many are also incredibly out dated. With a topic as old as centering there is a lot of old content out there on the subject, so I thought I would take some time to talk about a couple modern approaches to centering and leave out the old stuff.

Firstly I am only going to be talking about centering in the unknown. Because we are designing responsively/fluidly and for a range of devices it is very rare you know the rendered dimensions of any parent element. Or any element on a page for that matter. So I am going to look at a couple modern-ish techniques I have found to center both vertically and horizontally in the unknown.

Centering with Flexbox

Flexbox is a relatively new CSS property. It can do many things, but one very basic usage is centering something in the unknown.

.header {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100%;
}

.centered {
}

This is a simple way to center one element inside a parent of unknown dimensions. If you need to center multiple elements you can wrap them in a single div or other tag that makes semantic sense. Keep in mind the parent will need some sort of height, either set statically or using some javascript to fill the vertical space of the viewport. If the element which has display:flex is set to absolute you can use height:100% to fill the vertical space as well.

One thing to note though, when the flexed element is shorter than the element inside there are some weird overflow things happening. The scrollbar is activated but some of the child element gets cut off in some of my tests.

Centering with Transform

.header {
  position: relative;
}

.centered {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

This is a nifty trick. Since transforms only apply to the element, setting -50% gives us the perfect offset from the initial positioning to get a nice centred element. Again, the parent element needs a height applied to it. I usually use this technique with a full screen header, or something like that, when you want some text and call to action centred in the middle.

This method also does not suffer from elements being cut off when dealing with tight widths and heights like the flexbox method. Using transforms is also great if you need to move the element around, csstriggers.com/ says that “Changing transform does not trigger any geometry changes or painting, which is very good. This means that the operation can likely be carried out by the compositor thread with the help of the GPU.”