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');