how to center anything with transforms and position: absolute

always useful

by jack gold

HTML

<div class="container">
    <div class="block">Hi, i'm perfectly centered in my container, and I always will be, no matter what size this content or the container are. Try changing the dimensions in the img src to test this.
        <img src="http://placehold.it/300x200/0cd/fff" alt="i'm an image" />
    </div>
</div>

SCSS

* { box-sizing:border-box; }

.container {
    position:relative;
    min-width:500px; min-height:500px;
    background: #ccc;
    display:block;
}

.block {
    position:absolute;
    left:50%; top:50%;
    transform: translateX(-50%) translateY(-50%);
    
    padding:10px; border:1px solid white;
}