Skip to content

Instantly share code, notes, and snippets.

@mluton
Created February 28, 2012 20:19
Show Gist options
  • Save mluton/1934867 to your computer and use it in GitHub Desktop.
Save mluton/1934867 to your computer and use it in GitHub Desktop.
Web: Vertically Center Image with Dynamic Width
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Fluid Banner</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<style type="text/css" media="screen">
#container {
margin: auto;
width: 80%;
height: 300px;
border: 1px solid gray;
}
#image {
display: block;
width: 100%;
max-width: 480px;
margin: auto;
}
</style>
<script type="text/javascript">
function adjustImage() {
$("#image").css('margin-top', ($("#container").height() - $("#image").height()) / 2);
}
$(window).load(function() {
adjustImage();
$(window).resize(function() {
adjustImage();
});
});
</script>
</head>
<body>
<div id="container">
<img id="image" src="image.jpg"> <!-- native size is 480x300 -->
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment