Advertisement

Perfectly Center an Element with Transform

Video versionPerfect Center with CSS Transform.

The Problem

In CSS you can already perfectly center something, so why write this post? It’s because you can only do this if you know the exact widths and heights involved. This becomes troublesome when dealing with responsive webdesign where everything can shift every few hundred pixels or so.

.parent {
	width:400px;
	height:200px;
	position:relative;
	background:#ccc;
}

.child {
	width:100px;
	height:30px;
	position:absolute;
	top:10px;
	left:50%;
	background:#aaa;
}
1

The Solution

Enter CSS transforms. What you do with the transform is move the element 50% to the left, however instead of it moving 50% of the parent width, it moves 50% of it’s own width, meaning you can get it perfectly center inside the parent element.

Tip: You’ll need to add the -webkit- prefixed version or else the centering won’t work in Webkit based browsers like older versions of Chrome and mobile Safari. Quite a few older iPads run on the prefixed -webkit- version, so it’s worth adding in.

.child {
	-webkit-transform:translate(-50%, 0%);
	transform:translate(-50%, 0%);
}
2

You can also center it vertically, as well as horizontally, by adding the same -50% to the second transform value.

The first value is the left positioning and the second is the top positioning, just like with a background image.

.child {
	-webkit-transform:translate(-50%, 0%);
	transform:translate(-50%, -50%);
}

Advertisement

Web designer and developer from Southampton, UK.


Leave a Comment

Advertisement

Inspirational Newsletter

Join the newsletter to get the best articles, tutorials and exclusive freebies every two weeks.

No spam. You can unsubscribe at any time.