Problems with creating 'dead center' as jQuery plugin

I'm working on very, very simple jQuery plugin that simply changes position of element to the center of browser's window (horizontally and vertically). Often this is called 'dead center'.

jQuery.fn.dead_center = function() {

    var element;

    element = this;

    $(element).css({
        position: 'absolute',
        top: ($(window).height() - $(this).outerHeight()) / 2,
        left: ($(window).width() - $(this).outerWidth()) / 2
    });

}

Then I have <div /> with <h1 /> in it like this:

<div class="dead_center">
    <h1>Foo and bars.</h1>
</div>

At the end, I call my 'plugin' like this:

$(function() {

    $('.dead_center').dead_center();

});

Problem is that $('.dead_center') is only center on y-axis. Not x-axis!

Why this happens? Can't spot my mistake.

Thanks in any advice!

Answers


The default for a div is 100% width. (It's actually auto, but that's how auto works for block-level elements). So, it is centered horizontally. It's just taking up the whole horizontal area. Give the div a width, and you'll see.


Need Your Help

Metro App resolution on Windows 10

c# windows xaml windows-runtime

I have been working on win RT application for few months. Now I have upgraded to Windows 10 &amp; checking for compatibility. I am stuck at an issue wherein the windows scales the app to make maxim...

Is it possible to do a HMAC with wincrypt?

c++ c winapi hmac cryptoapi

I've been trying to perform a straight forward SHA256 HMAC using wincrypt/cryptoapi/Cryptography API: Next Generation (CNG) and i'm really struggling. My target is Windows 8.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.