Center 2.0

Created Wednesday 17th of September 2008 by Andreas Lagerkvist
Copyright © 2008 Andreas Lagerkvist (andreaslagerkvist.com)

What it Does

This little pluggy centers an element on the screen using either fixed or absolute positioning. Can be used to display messages, pop up images etc.

How to Use

jQuery('#my-element').center(true); would center the element with ID 'my-element' using absolute position (leave empty for fixed).

Example

I should be fixed centered

The paragraph above and the paragraph beneath this one are centered. They should be in the middle of the viewport.

I should be absolutely centered

Example Code

HTML

<div id="jquery-center-example">
<
p>I should be fixed centered</p>

<
p>The paragraph above and the paragraph beneath this one are centeredThey should be in the middle of the viewport.</p>

<
p>I should be absolutely centered</p>
</
div>

JS

jQuery('#jquery-center-example p:first-child').center();
jQuery('#jquery-center-example p:last-child').center(true);

Source Code

jQuery.fn.center = function (absolute) {
    return 
this.each(function () {
        var 
jQuery(this);

        
t.css({
            
position:    absolute 'absolute' 'fixed'
            
left:        '50%'
            
top:        '50%'
            
zIndex:        '99'
        
}).css({
            
marginLeft:    '-' + (t.outerWidth() / 2) + 'px'
            
marginTop:    '-' + (t.outerHeight() / 2) + 'px'
        
});

        if (
absolute) {
            
t.css({
                
marginTop:    parseInt(t.css('marginTop'), 10) + jQuery(window).scrollTop(), 
                
marginLeft:    parseInt(t.css('marginLeft'), 10) + jQuery(window).scrollLeft()
            });
        }
    });
};

Download

Plug-in

Requires

Post a Comment

blog comments powered by Disqus

Random jQuery Plug-ins

  • Slide Presentation

    A sort of slide/presentation kind of plug-in. Displays sliding images with text floating on top. This one's pretty specific but perhaps someone will f...

    Details

  • Numeric DL

    This tiny plug-in numbers definitions in a definition-list if there are more than one definition for a term. Can be useful for FAQs, actual lists of d...

    Details

  • Form to Link

    Run this plug-in on a form or an input[type=submit] and it will insert a link after the element you run it on which, on click, will submit said form.

    Details

More Plug-ins

Recent Comments

Powered by Disqus