Keep elements horizontally and vertically in center

In UI/UX world, sometimes we are facing with elements with unknown width and height, so here is the way to keep a relative or absolute element horizontally and vertically in center without using flex or other tricks!

# HTML code
<parent>
    <child>Some text to show always in center!</child>
</parent>
# CSS code
parent{
    position: relative;
    width: 50vw;
    height: 50vh;
    left: 50%;
    top: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    display: block;
    border:1px dashed;
}
parent child{
    position: absolute;
    border: 1px solid green;
    left: 50%;
    top: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    margin: 0;
}

Leave a Reply

Your email address will not be published.