Center div horizontally and vertically (jquery)

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

by KURO KUMO

HTML

<div class="container">
  <img class="content" src="http://placehold.it/300x200/" />
</div>

CSS

.container {
  position: relative;
  background: #c0c0c0;
  width: 100%;
  height: 100hv;
}

.content img {
  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);
}