How to make a container center both horizontally and vertically?

Leave a Comment
There are multiple ways of doing this.

1. Using Positions : We can use position relative and absolute. 

How? 

Make the window or the wrapper container as relative and set width and height as 100%.
Make the inner div(which we need to place in the center) position absolute and all values as 0. Suppose the inner div is having id as 'centered-div'. Then our css would be.

#centered-div {
   position: absolute;
   top: 0;
   right : 0;
   bottom: 0;
   left: 0;
   margin: auto;
}


2. Using Table Structure : We can set the wrapper as table and the inner div as table-cell

How? 

We can set the window or the wrapper as a table and the inner container('#centered-div ') should be set as table-cell. And make the vertical alignment for the table as middle. See the details below.

#wrapper{
   display: table;
   vertical-align: middle;
}
#centered-div {
   display: table-cell;
}

3. Using Margin and Position : 

How ? 

We can make the inner div position relative or absolute, top 50% and margin-top should be negative value of the half height of the inner div. Margin left and right should be auto.

#wrapper{
   position: relative;
   width: 100%;
   height: 100%;
}

#centered-div {
   height : 400px;
   position: absolute;
   top: 50%;
   margin-top: -200px;  // half of the height and negative
}
Next PostNewer Post Previous PostOlder Post Home

0 comments:

Post a Comment