Centering Vertically

November 2nd, 2010 Leave a comment Go to comments

There are several possilbities depending on the markup that is availiable.

1) Centering text in a block with fixed height

Solution: Use line-height with same height as the div.

<style type="text/css">
div.ht-fixed-height {
  border: 1px solid red;
  height: 50px;
  line-height: 50px;  
}
</style>
<div class="ht-fixed-height">
My Text in the middle.
</div>

 

2) Centering bullets in a list

Solution: use a background-image with background-position: left center (or 2px center).

<style type="text/css">
ul.centered-bullets {
  margin: 0;
  padding: 0;
}
ul.centered-bullets li {
  margin: 0;
  padding: 0 0 0 20px;
  background-image: url(http://live.premiumweb.de/images/bullet.jpg);
  background-position: 2px center;
  background-repeat: no-repeat;
  border: 1px solid blue;
  list-style-type: none;
}
</style>
<ul class="centered-bullets">
  <li>My First</li>
  <li>My Second <br /> is bigger</li>
</ul>

Hint: If your image is a little to high, make the image a little taller with transparent pixels on the bottom (or vice versa).

 

3) Centering image and text in a div with fixed height

Solution: use vertical-align on the image.

<style type="text/css">
div.fixed-height-image {
  height: 50px;
  border: 1px solid blue;
}
div.fixed-height-image img {
  margin-right: 10px;
  vertical-align: middle;
}
</style>
<div class="fixed-height-image">
  <a href="#"><img src="http://live.premiumweb.de/images/sample.jpg" alt="sample" />Text</a>
</div>

 

4) Centering images with multiple elements in a grid.

Solution: work with float and line-height.

<style type="text/css">
div.multi-grid ul {
  width: 200px;
  float: left;
  border: 1px solid red; 
  margin: 0 0 0 10px;
  padding: 0;
}
div.multi-grid li {
  height: 50px;
  border: 1px solid blue;
  margin: 0 0 10px 0;
  padding: 0;
  list-style-type: none;
}
div.multi-grid img {
  float: left;
}
div.multi-grid span {
  display: block;
  height: 50px;
  line-height: 50px;
  margin-left: 10px;
  float: left;
}
</style>
<div class="multi-grid">
<ul>
  <li><a href="#"><img src="http://live.premiumweb.de/images/sample.jpg" alt="sample" /><span>Text</span></a></li>
  <li><a href="#"><img src="http://live.premiumweb.de/images/sample.jpg" alt="sample" /><span>Text</span></a></li>
</ul>
<ul>
  <li><a href="#"><img src="http://live.premiumweb.de/images/sample.jpg" alt="sample" /><span>Text</span></a></li>
  <li><a href="#"><img src="http://live.premiumweb.de/images/sample.jpg" alt="sample" /><span>Text</span></a></li>
</ul>
</div>

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