CSS trick to place div in centre

For fix and relative positioned divs, if you already know the width or height. You can place them easily in centre horizontally or vertically.

For example, you have a div with width 400px.

<div style="width:400px;">


To place it in the centre of it parent div, you can set the left:50% and margin-left:-200px;

<div style="width:400px;position:relative;left:50%;margin-left:-200px;">


Set it left 50% of the parent div’s size, and then set its left margin to half size of its width. Make sure your position is relative or fixed. It will sit in the centre of your page.

It also works for vertical divs, set top 50% and top margin to its half size of the height. E.g.

<div style="height:400px;position:relative;top:50%;margin-top:-200px;">


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s