Center element inside of a div container


/ Published in: JavaScript
Save to your folder(s)

Position of the element to center needs to be relative to the container.


Copy this code and paste it in your HTML
  1. function CenterInsideDiv(divContainer,elementToCenter) {
  2. var divContainerHeight = divContainer.height();
  3. var elementToCenterHeight = elementToCenter.outerHeight();
  4.  
  5. var elementNewTop = divContainerHeight / 2 - elementToCenterHeight / 2;
  6.  
  7. elementToCenter.css({ top: elementNewTop, left: 0 });
  8. }
  9.  
  10. // call function like this
  11. CenterInsideDiv($("#elementToCenterId").parent(), $("#elementToCenterId"));

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.