Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering element inside an element (jQuery)

<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!

like image 317
eozzy Avatar asked Dec 23 '09 17:12

eozzy


People also ask

How do you center text within an element?

Center Align Text To just center the text inside an element, use text-align: center; This text is centered.

How do I center in jQuery?

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

How do you center within a parent element?

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.


2 Answers

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

like image 185
jsturtevant Avatar answered Oct 15 '22 13:10

jsturtevant


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

like image 30
WhyNotHugo Avatar answered Oct 15 '22 15:10

WhyNotHugo