<div class="preview">
<span class="center">This will be centered</div>
</div>
Preview has fixed width (120x120), but span may contain anything (image, text). How do I center it vertically and horizontally using jQuery? I looked up some snippets but they all center elements inside the 'body' not another element. I'd like to avoid use a 'plugin' for this if possible.
Many thanks!
Center Align Text To just center the text inside an element, use text-align: center; This text is centered.
There is a way to center a <div> element to the middle of a page using only jQuery. To use the above function, you should choose the <div> element to center and pass it through your new function: $(element). center();
Like last time, you must know the width and height of the element you want to center. Set the position property of the parent element to relative . Then set the child's position property to absolute , top to 50% , and left to 50% . This just centers the top left corner of the child element vertically and horizontally.
You could add your own function to jquery:
// Centers on div
jQuery.fn.center = function (div) {
this.css("position", "absolute");
var position = div.position();
this.css("top", Math.max(0, ((div.height() - this.outerHeight()) / 2) + position.top) + "px");
this.css("left", Math.max(0, ((div.width() - this.outerWidth()) / 2) + position.left) + "px");
return this;
};
Use:
$('#ajxload').center($('#mapWrapper')).show();
Took the concept from the code at Using jQuery to center a DIV on the screen
The latest jQuery UI has a position component:
$("#myDialog").position({
my: "center",
at: "center",
of: window
});
Doc: http://jqueryui.com/demos/position/
Get: http://jqueryui.com/download
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With