user776942
user776942

Reputation:

How do I horizontally center this alert?

I'm trying to display an alert when a user clicks a button but can't figure out how to horizontally center an alert. I'd like the alert to stay within #main. See this fiddle.

thanks!

Upvotes: 2

Views: 10150

Answers (4)

sonnyhe2002
sonnyhe2002

Reputation: 2121

#message{
  display: none;
  position: relative;
  top: 50%;
  text-align: center;
}

Upvotes: 2

Joe Valeriana
Joe Valeriana

Reputation: 610

As the solution through css proposed by @Darkwater is correct, some time ago I created this plugin for jQuery, which still uses the CSS, so that it can be quickly reused on multiple objects.

Create a new method for jQuery called center:

$.fn.center = function() {
    this.css("position","absolute").css("z-index","5000")
    .css("top","50%").css("left","50%")
    .css("margin",(-(this.height()/2))+"px 0 0 "+(-(this.width()/2))+"px"); 
    return this;
};

Then bind it to your object (your alert div#message in this case) just after the .show():

$("#message").show().center();

And the div will be centered both vertically and horizontally.

EDIT: remember to bind the method center() just after the method show() or similar that makes visible the element to the DOM, because, as far as I know, jQuery can't handle properly hidden elements.

Upvotes: 3

Mr. Alien
Mr. Alien

Reputation: 157334

Your markup and CSS positioning is actually wrong, instead of using position: fixed; use position: relative; for #main and position: absolute; for #message and also shift your message div in #main div

And about the calculation part, when you want to center a div, you've to give top: value (-)minus height of the div to bring it vertically center..

My Fiddle

Upvotes: 2

Darkwater
Darkwater

Reputation: 1386

Make sure that #main has a position other than static, then assign the following rules to the alert:

position: absolute;
left: 50%;
top: 50%;
margin-left: -width;
margin-top: -height;

Replace width and height with the correct values.

Upvotes: 4

Related Questions