0

Posted: December 10th, 2009    By: Devin Walker   
CSS IconCascading style sheets make is very easy to center objects vertically. This may be an image or some text that you wish to align properly for whatever reason. For this tutorial we will demonstrate how to vertically align some text then an image using an easy and W3C compliant method. Then I will show you how to place text or images in the absolute middle or center.

Vertically Align Text:

1. Create a new HTML file in your favorite editor and let's begin by creating a container for our object that we want vertically centered:

[inline lang="HTML"]
<div id="container">
</div>

Next, add some text in a paragraph tag in between the div tags.

<div id="container">
<p>I am text, look at me!</p>
</div>

2. Apply the following CSS to the container div:

#container {
      display:table-cell;
      height:120px;
      vertical-align:middle;
}

Result:

This is my text, hello look at me! I'm vertically centered and I can keep on being centered no matter how long my text continues on for... see the light-yellow background? That's my container





Vertically Align an Image:

1. Now let's create another div container for our image we want vertically centered:

<div id="container_image">
</div>

Next, add an image in between the div tags.

<div id="container_image">
<img src="path/to/image.jpg"/>
</div>

2. Again, apply the following CSS to the container_image div:

#container_image {
      display:table-cell;
      height:120px;
      vertical-align:middle;
}

Result:

Cool Icon

Horizontally and Vertically Align an Image:

1. For our last example, create yet another div container for our image:

<div id="container_image">
</div>

Next, add the image again in between the div tags.

<div id="container_image">
<img src="path/to/image.jpg"/>
</div>

2. Once more, apply the following CSS to the container_image div:

#container_image {
      display:table-cell;
      height:120px;
      vertical-align:middle;
}

#container img {
      margin:0 auto;
}

Result:

Cool Icon

Leave a Reply