Suja Shyam
Suja Shyam

Reputation: 971

Showing div at the center of the webpage

I have a div showing "Please wait". The markup for the div is

<div id="pleaseWait" class="divOuterPleaseWait" style="left:expression((documentElement.clientWidth-this.offsetWidth)/2);top:expression(documentElement.scrollTop+((documentElement.clientHeight-this.clientHeight)/2 ));">Please Wait...</div>

This is working fine with IE7. In IE7 the div is show at the center of the page. But excepted behariour is not optained in other browsers (ie. IE8,IE9,FireFox,Google Chrome etc). What should i give to get this working in all browsers? Also can I move the inline style to the my CSS?

Upvotes: 0

Views: 352

Answers (6)

KooiInc
KooiInc

Reputation: 122996

See this SO answer, or this jsfiddle (press the 'confirm' button). The css you showed in your question is browser specific (especially: IE). In javascript you can center an element by determining the 'viewport' dimensions (height/width of the available screen) and position your element relative to those dimension. The links here demonstrate a way to do that.

Upvotes: 1

BlueCacti
BlueCacti

Reputation: 10844

Using auto as margins and defining a width and hight should be enough

<div style="width:200px;height:50px;margin:auto;text-align:center">Please wait ...</div>

If you only want to center verticaly, use margin: 0 auto;

PS: if you want to be more XHTML-correct, put your CSS in a CSS-file and use a class or a id to define the css-styling

I've answered this before: How to set the div in center of the page

Upvotes: 0

tomraithel
tomraithel

Reputation: 968

CSS expressions are only working in IE. However, it´s generally not a good idea to use them because they are not W3C conform and in addition they can be very slow when you make heavy use of them.

The CSS attribute position: fixed could help you here:

#pleaseWait {
    width: 400px;
    height: 200px;
    position: fixed; /* IE8+ */
    left: 50%;
    top: 50%;
    margin-left: -200px; /* half of width*/
    margin-top: -100px; /* half of height*/
}

If you have to still support <=IE7 you have to use JavaScript (but not within the CSS definition!)

Upvotes: 0

kaj
kaj

Reputation: 5251

Another approach:

<div style="text-align:center;width=200px;margin-left:auto;margin-right:auto">Please wait...</div>

Upvotes: 0

Andre Loker
Andre Loker

Reputation: 8408

A good way to center a div is to use fixed positioning, top and left set to 50% and left and top margin to the negative of half of the width/height:

http://jsfiddle.net/fLa4S/

Upvotes: 3

Tim M.
Tim M.

Reputation: 54417

It doesn't work in "other browsers" because you are using expressions in your CSS which are 1) incredibly bad for a variety of reasons (slow, deprecated, non-standard) and 2) unnecessary.

You can use pure CSS positioning (percentages and negative margins) or a little JavaScript (jQuery makes this very easy) to accomplish the same thing in all browsers.

Upvotes: 0

Related Questions