Center div horizontally and vertically (jquery)

A technique to center an image inside a div by using a jQuery script

by juErik

HTML

<div id="container">
  <img id="content" src="foo.jpg" />
</div>

CSS

#container {
  position: relative;
  background: #c0c0c0;
  width: 100%;
  height: 200px;
}

#content {
  position: absolute;
  display: inline-block;
  background-color: #fff;
  width: 30%;
  height: auto;
  border: 1px solid black;
}

JavaScript

$(window).load(function() {
  centerContent();
});

$(window).resize(function() {
  centerContent();
});

function centerContent() {
  var container = $('#container');
  var content = $('#content');
  content.css("left", (container.width() - content.width()) / 2);
  content.css("top", (container.height() - content.height()) / 2);
}