Skip to content

Instantly share code, notes, and snippets.

@davestevens
Created August 27, 2014 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davestevens/ce1db5334ca06c487d39 to your computer and use it in GitHub Desktop.
Save davestevens/ce1db5334ca06c487d39 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<style>
.vertically_align {
width: 256px;
height: 256px;
overflow: hidden;
}
.vertically_align:before {
content: "";
vertical-align: middle;
display: inline-block;
height: 100%;
}
.vertically_align img {
vertical-align: middle;
display: inline-block;
}
</style>
</head>
<body>
<h1>This will work</h1>
<div class="vertically_align"><img src="http://read.pudn.com/downloads73/sourcecode/windows/11773/lena(256)__.jpg"/></div>
<h1>This will not work (due to there being whitespace?)</h1>
<div class="vertically_align">
<img src="http://read.pudn.com/downloads73/sourcecode/windows/11773/lena(256)__.jpg"/>
</div>
</body>
</html>
@danjordan
Copy link

Basically the browser is inserting spaces before and/or after the image because it's treating the content inside vertically align as inline (basically like text). This makes the browser think the content content is wider than 256px and drops it onto the next line, as it would with text.

You can see this by changing .vertically_align width to 260px and seeing it work. No idea why :after fixes it, but it does.

@davestevens
Copy link
Author

Cheers!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment