3

What is the most compatible method to center (horizontal and vertical) align a <div> on a screen?

I am currently using CSS with:

div.myBlock
{
    position:absolute;

    width:500px;
    left:50%;
    margin-left:-250px;

    height:500px;
    top:50%;
    margin-top:-250px;
}

This works fine in modern browsers, but messes up in older chrome's/firefox's etc.

It is for a basic pop-up such as the pop-ups on FaceBook.

Any ideas? Maybe using JS/jQuery can be effective?

Pangolin
  • 7,284
  • 8
  • 53
  • 67
  • 2
    You do not need to use javascript at all. Your solution above should work in all browsers. What version of firefox chrome doesnt it work in? I would like to see this – Mark Steggles Oct 06 '11 at 13:35
  • I cant remember, but I showed my site to several friends and 2 (different ones) bugged out. – Pangolin Oct 06 '11 at 13:48
  • What version of CSS? It could be you're using something from a newer version of CSS that old Firefox/Chrome browsers don't know what to do with. – FloppyDisk Oct 06 '11 at 14:45
  • May it be because I only use ` – Pangolin Oct 06 '11 at 15:11
  • 1
    worth a try.. but the css you posted in your question will work in all browsers.. even IE6. – Mark Steggles Oct 06 '11 at 15:28

1 Answers1

2

i'm using this function to center my stuff's, have been working so far.

the source is from here, not remember from who.

    // $(element).center();
    jQuery.fn.center = function () 
    {
        this.css("position","absolute");
        this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
        this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
        return this;
    }

edit:

found:

using-jquery-to-center-a-div-on-the-screen

Community
  • 1
  • 1
Ricardo Binns
  • 3,228
  • 6
  • 44
  • 71