Advertisement

Perfect Center with CSS Transform

Ever wanted to perfectly center with CSS and not have to rely on JavaScript? Then I may have a solution for you.

The problem with absolute positioning is that elements are moved according to the parent, so they get positioned too far away from the center. It’s not such a problem on a static design, but on a responsive site, things starts to breakdown rather badly.

In this video quick-tip, I show you how to perfectly center an element using the CSS transform and positioning properties.

Here’s the code I used in the video, ready for you to copy and paste into you own project:

/* Center with Transform */
.parent-element {
	width:600px;
	height:400px;
	margin:50px auto;
	position:relative;
	background:#f6f7f8;
}

.child-element {
	width:200px;
	height:200px;
	position:absolute;
	top:50%;
	left:50%;
	-webkit-transform:translate(-50%, -50%);
	transform:translate(-50%, -50%);
	background:#e2e2e4;
}

Have a look at CSS transform and translate on Can I use for a better overview of where it’s supported.

If you have any questions, please let me know in the comments!

You might also like: Sublime Text 3 Tweaks for Beginners.

Advertisement

Web designer and developer from Southampton, UK.


Leave a Comment

Pingbacks (1)

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.