April 29, 2012

Using jQuery for vertical and horizontal centering

Question by JamesCharless

I’m using jQuery to horizontally center a div element that doesn’t have a default width. I’m using the following code, but it’s not working. if anyone could help me to understand why, it’d be very helpful. PS, I the height has a default height of 20, so that’s where the -10px comes from.

var w = ($(".notec").width() + 51) / 2;
$(".buttons").css("margin", "-10px 0 0 -" + w + "px");

Answer by Starx

Centering with respect to .notec. Width is not needed if the element is displaying as block element.

var h = ($(".notec").height() - $(".buttons").height()) / 2;
$(".buttons").css("margin", h+"px auto 0 auto');

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!