I have a modal script. I need the modal box to be centered in the middle of the screen.

But there is a catch.

The modal box can be of a different sizes and i would like to have a offset dependent on the height of my modal box.

If i have a dinky modal box, and a large screen, i don't want the user to look down the page to see the modal box.

And on the other hand, i dont want the to of a large modal box to be cut off the top of the screen.

I have thought about it and basically:

the shorter the modal is, the closer towards the top of the screen it needs to be offset.

the taller the modal is, the more near the center of the scree it needs to be offset.

I have thought about just setting the modal at a set amount of px from the top of the screen, but where the hell is the fun in that?

here is my code:

var mh = $this.height(),
			mw = $this.width(),
			ww = $window.width(),
			wh = $window.height(),
			vp = (wh/2)-(mh/2),
			hp = (ww/2)-(mw/2);

		$this
			.css({
				display: 'block', 
				top: vp, 
				left: hp,
			})
			.animate({opacity: 1}, 300);

I have come up with something:

vp = ((wh/2)-(mh/2)) * (mh / (wh * .5))

Let me know if that looks good to you guys. It seems to work ok for now.

I'd like to know if someone can come up with something better.

Thanks in advance

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.