Centering Block Level Elements Horizontally
If you have a block level element (like a div), and you want to center it horizontally, you can use auto margins. However, this requires the element to have a set width:
HTML
<div class="center-block">Centered block</div>
CSS
.center-block { border: 3px dashed powderblue; margin-left: auto; margin-right: auto; width: 50%; /* or any specific width */ }
If the element is not block level by default, you can set it’d display property to block like so:
.center-block { display: block; }
Centering Elements Vertically
In order to center an element vertically, you will need to use positioning, like in the example below:
HTML
<fieldset class="relative-parent"> <legend> Relative parent </legend> <div class="absolute-child">Absolute child</div> </fieldset>
CSS
.relative-parent { position: relative; width: 100%; height: 160px; border: 3px dashed powderblue; } .absolute-child { width: 160px; height: 100px; margin: 0 auto; position: absolute; top: 50%; left: 0; right: 0; transform: translateY(-50%); background-color: crimson; }