Lastweek, I worked on project and stuck at make a vertical-align content center. I was spent all night long for searching. Now, when project completed, I write this post to share what I have learned. Hope it help for you to vertical-align content everything
Now! let’s vertical-align
Method 1
The solution is:
- Specify the parent container as position:relative or position:absolute.
- Specify a fixed height on the child container.
- Set position:absolute and top:50% on the child container to move the top down to the middle of the parent.
- Set margin-top:-yy where yy is half the height of the child container to offset the item up.
An example of this in code:
<style type="text/css"> #myoutercontainer { position:relative } #myinnercontainer { position:absolute; top:50%; height:10em; margin-top:-5em } </style> ... <div id="myoutercontainer"> <div id="myinnercontainer"> <p>Hey look! I'm vertically centered!</p> <p>How sweet is this?!</p> </div> </div>
In your browser, the above example renders as:
Hey look! I’m vertically centered!
How sweet is this?!
Method 2
This method requires that you be able to satisfy the following conditions:
- You have only a single line of text that you want to center.
- You can specify a fixed-height for the parent element.
If you can accept the above necessities, the solution is:
- Set the line-height of the parent element to the fixed height you want.
An example of this in code:
<style type="text/css"> #myoutercontainer2 { line-height:4em } </style> ... <p id="myoutercontainer2"> Hey, this is vertically centered. Yay! </p>
In your browser, the above example renders as:
Hey, this is vertically centered. Yay!
Method 3
The CSS property transform is usally used for rotating and scaling elements, but with its translateY function we can now vertically align elements.
So, let try to do this
.element { position: relative; top: 50%; transform: translateY(-50%); }
That’s all you need. It is a similar technique to the absolute-position method, but with the upside that we don’t have to set any height on the element or position-property on the parent. It works straight out of the box. To ensure browser compability, remember to add the proper vendor prefixes. At the time of writing, you need -ms-transform and -webkit-transform to make sure it works everywhere.
Example:
.text p { position: relative; left: 1%; top: 50%; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%); } section.text { box-shadow:0px 0px 0px 2px black inset; height: 150px; }
HTML
<section class="text"> <p>I'm vertically aligned! Zindo.info</p> </section>
And it will look like this
I’m vertically aligned! Zindo.info