Friday, April 17, 2015

How to place any element vertically center inside another using CSS

Placing an element vertically center inside of another element is easy with CSS. I will show you how to do it.



There is an CSS attribute called "transform", we gonna use that. Here is the reference for transform:translate


Placing element vertically center inside another div

CSS for placing any element vertically center 


Make Y axis translate about 50 percent 

.v-center {

    position:relative;

    top:50%;

    transform: translateY(-50%);

}



Below is an example to show how I positioned a DIV inside another div to make it vertically center.





Creating Simple HTML and place our element inside a holder


<div class="holder">

    <div class="v-center">

        This is my element placed in the center of another div

    </div>

</div>




Applying CSS 

.holder {

    margin-top:50px;

    padding:20px 5px;

    height:200px;

}


.v-center {

    text-align:center;

    position:relative;

    top:50%;

    transform: translateY(-50%);

}


Browsers Compatibility for vertical ceter css

To make it browsers compatible, you might have to use "-ms-transform" and "-moz-transform"

.v-center {

    text-align:center;

    position:relative;

    top:50%;

    transform: translateY(-50%);

    -ms-transform: translateY(-50%);

    -moz-transform: translateY(-50%);

}




I created a fiddle here : http://jsfiddle.net/mannemvamsi/ctwxvapL/


2 comments: