I use two main methods for aligning divs centrally on the vertical plane, the first is quick & dirty but pretty much 100% effective.

All we’re doing here is wrapping the element in a table cell (within a row, table body and table itself) which will fill the height of the containing element and align in the middle of the space.

<table class="centred" cellpadding="0" cellspacing="0" border="0"><tbody><tr><td>
  <!-- Centralized conten goes here -->
</td></tr></tbody></table>
<style type="text/css">
  .centred {
    width: 100%;
    height: 100%;
  }
  .centred td { vertical-align:middle; text-align:middle; }
</style>

This is supported relatively uniformly across all browsers since always, but the drawbacks include requiring access to the template to insert the html (i.e. it’s not a pure css solution) and you know, just tables.

If for whatever reason I cannot get access to the template files or I’m bored of tables I might use use the following:

<div class="container">
  <p class="centre">
    <!-- in the centre! -->
  </p>
</div>
<style type="text/css">
  .container {
    width: 50px;
    height: 50px;
    display: block;
    color: #fff;
    text-align: center;
    position: relative;
    -webkit-transform-style: preserve-3d;
    -moz-transform-style: preserve-3d;
    transform-style: preserve-3d;					
  }
  .centre {
    position: relative;
    display: block;
    top: 50%;
    -webkit-transform: translateY(-50%);
    -moz-transform: translateY(-50%);
    transform: translateY(-50%);			
  }
</style>

In which we set the height of the container and it’s position as relative, then the element within is also define as relative so we can shift it halfway down from the top then nudge it back up half its own height (the translateY property). And thusly we end up with the .centre div floating right in the middle.
This method is not supported on the oldest browsers especially 10 and under. If you know the height for both elements apply the formula

(Container Height – Centred Element Height) / 2

to get a the actual top value and use that instead of the transform rules – you could even do it in the css using the calc() function ;).

There are plenty of other good methods to achieve this including using js or jQuery all with their own advantages and drawbacks so being flexible is one of the surefire ways to success!

Leave a Reply

Privacy & more..

Cookie Consent Policy