Search code examples
jquerycssheightcentervertical-alignment

Centering element inside an element (jQuery)


<div class="preview">
  <span class="center">This will be centered</div>
</div>

Preview has fixed width (120x120), but span may contain anything (image, text). How do I center it vertically and horizontally using jQuery? I looked up some snippets but they all center elements inside the 'body' not another element. I'd like to avoid use a 'plugin' for this if possible.

Many thanks!


Solution

  • Since you don't mind using jQuery, you can use the Center Element Plugin

    It's as simple as doing:

    $(".preview").center();