How to center a div

The most googled search that we always forget. How to center a div?!

No fancy things here, just click a method below and go.

Horizontally

Your HTML:

                
                    
                        <div>
                        class="horizontally">
                    
                    
<p>A lovely horizontally positioned div just for you.</p>
</div>

Your CSS:

                
                    
                        .horizontally {
                        
margin: auto;
border: 2px solid #000000;
width: 50%;
}

Result:

A lovely horizontally positioned div just for you.

Vertically

Your HTML:

                
                    
<div class="veritcally">
<p>A pretty vertically positioned div just for you.</p>
</div>

Your CSS:

                
                
.vertically {
position: relative;
top: 50%;
transform: translate(0, -50%);
border: 2px solid #000000;
}

Result:

A pretty vertically positioned div just for you.

Horizontally & Vertically

Your HTML:

                
                    
<div class="hVParent">
<div class="horizontally-vertically">
<p>A beautiful horizontally AND vertically positioned div just for you.</p>
</div>
</div>

Your CSS:

                
                
.hVParent {
position: relative;
}

.horizontally-vertically {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border: 2px solid #000000;
}

Result:

A beautiful horizontally AND vertically positioned div just for you.

Div within a Div

Your HTML:

                
                    
<div class="parent-div">
<div class="child-div"><p>Inception div - queue inception music.</p></div>
</div>

Your CSS:

                
                
.parent-div{
background: #808080;
justify-content: center;
display: flex;
height: 250px;
width: 250px;
}

.child-div{
background: #D3D3D3;
align-self: center;
padding: 1rem;
}

Result:

Inception div - queue inception music.


Source: Multiple Stackoverflow threads..
Questions? Concerns? See something to fix? Email me :)