How to

center a

DIV

Using Flexbox

HTML

                    
<div class="outside">
    <div class="inside"></div>
</div>
                

CSS

                    
.outside { 
    width: 400px;
    height: 400px;
    background-color: #ccc;
    display: flex;
    align-items: center;
    justify-content: center;
}

.inside {
    background-color: pink;
    height: 200px;
    width: 200px;
}
                

Example

inside

Using flexible display

HTML

                    
<div class="outside">
    <div class="inside">inside</div>
</div>
                

CSS

                    
.outside {
    width: 400px;
    height: 400px;
    background-color: #ccc;
    display: flex;
}

.inside {
    background-color: pink;
    margin: auto;
    height: 200px;
    width: 200px;
}
                

Example

inside

Using margin-inline

CSS

                    
.element {
    max-width: fit-content;
    margin-left: auto;
    margin-right: auto;
}
                

Example

inside

Using grid

Besides the method above, you can also set margin-left and right to auto, so the browser will automatically center the element specified.

HTML

                    
<div class="outside">
    <div class="inside">inside</div>
</div>
                

CSS

                    
.outside {
    display: grid;
    place-content: center;
}
                

Example

inside

Using absolute positioning

HTML

                    
<div class="outside">
    <div class="inside">inside</div>
</div>
                

CSS

                    
.outside {
    width: 400px;
    height: 400px;
    background-color: #ccc;
    position: relative;
}

.inside {
    background-color: pink;
    height: 200px;
    width: 200px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
                

Example

inside

Using the browser window

CSS

                                            
.element {
    position: fixed;
    inset: 0px;
    margin: auto;
}
                

Using text alignment

HTML

                    
<div class="outside">
    <div class="inside">inside</div>
</div>
                

CSS

                    
.outside {
    width: 400px;
    height: 400px;
    background-color: #ccc;
    text-align: center;
}

.inside {
    background-color: pink;
    line-height: 400px;
}
                

Example

inside

Compatibility

Method Chrome Firefox Safari Edge
Using flexbox Yes Yes Yes Yes
Using flexible display Yes Yes Yes Yes
Using margin-inline Yes Yes Yes Yes
Using grid Yes Yes Yes Yes
Using absolute positioning Yes Yes Yes Yes
Using the browser window Yes Yes Yes Yes
Using text-alignment Yes Yes Yes Yes
Should I add a method, so anyone can upload their own CSS snippets? If yes, write a comment on github on the index.html file or if you're in the Summer of Making, DM me (BrunoGC13)