Vertical Aligning with CSS

August 12th, 2009

Vertically aligning with CSS is not quite as easy as when you use tables for page layout. With tables all you need to do is set a table cell’s vertical align attribute to middle. But, using tables for page layout is bad practice and below are examples of how to vertically align without them.



Vertically Aligning a Single Line of Text.

All you need to do here is set the line height and height of element to the same value. This is definitely the best solution if you know all that needs to be vertically aligned is a single line of text.

<html>
<head>
<style type="text/css">
#inner{
	height: 50px;
	border: 1px solid black;
	line-height: 50px;
}
</style>
</head>

<body>
    <p id="inner">
		vertically aligned line of text
    </p>
</body>
</html>




Vertically Aligning Any Content

With this solution you can vertically align any content you want.

<html>
<head>
<style>
  	#outer{
		height: 400px;
		border: 1px solid black;
		display: table;
	}

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

	#inner{
		border: 1px solid black;
	}

</style>
</head>

<body>
  <div id="outer" >
    <div id="middle">
      <div id="inner">
        any content<br>
        any height<br>
        everything is vertically centered
      </div>
    </div>
  </div>
</body>
</html>


CSS

  1.  
    No comments yet.
     
Post a Comment
  1. No trackbacks yet.
You must be logged in to post a comment.