Tuesday, 28 October 2014

Vertical and Horizontal Center Alignment of Element(CSS)

    Vertical and Horizontal Center Alignment of Element(CSS)

This is for those who knows CSS.


As you know you can set specific element in the center of it's parent using "margin: auto;".


Using CSS position property.

With this property you can set your element without affecting the others.
Im going to show you how to set the element in the center verticaly and horizontaly. To do that you need to use also the margin: auto; property.
We simply add :

margin: auto;

position: absolute;


  • if we want to set it centered horizontaly we do that:

margin: auto;
position: absolute;
left: 0;
right: 0;

Now when you resize the page it wil be always at the center.



  • You can also set vertical center alignment by doing this :
margin: auto;
position: absolute;
top: 0;
bottom: 0;


  • Or set centered alignment for horizonal and vertical :
margin: auto;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;

Now no matter what you resize, the heigth or the width of the page the element will be always at the center of the page.


EXAMPLE:


<html>

<head>
<title></title>
<style>
.myDiv {
width: 300px;
height: 230px;
background: red;
margin: auto;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
</style>
</head>
<body>
<div class="myDiv"></div>
</body>
</html>



#easilylearnhtml