One of the things that I find myself going back to lately is centring a div or any DOM object on a page, and having it appear centred no matter what size of screen the user views it on. In short, how to make it responsive.

And it might come as a surprise to many people, but the solution for this is actually quite simple. Use this simple CSS trick and your div will be centred on the page, whether you’re viewing it on a laptop or mobile device.

Let’s start with the HTML:

<div id="box"> </div>

Now, let’s say I want to make this div a 50 x 50 px box with a red border and a black background. More importantly, I want it to be centred. We’re going to use CSS to make this happen:

#box {
/* first, let's set the height, width, 
border and background colour of the div */
height : 50px; 
width: 50px; 
border: 2px solid red; 
background-color: black; 
/* Now, make it centred */ position: absolute; top:0; bottom: 0; left: 0; right: 0; margin: auto; }

And that’s all you need! Now, anything you put inside your #box div will show up centred on the page. This is an easy way to showcase images or create responsive websites.

You can play around with a demo of this tutorial here.

Happy coding!