Created
August 27, 2014 15:09
-
-
Save davestevens/ce1db5334ca06c487d39 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.