I\'m looking for a way to vertically align a block element to an image. On my site this image would dynamically change in height and width so I\'d need the vertical alignmen
The trick is to add a couple layers of wrapper-divs. The first layer is set to white-space: nowrap
and max-width:50%
which means that the elements inside can't wrap, and are constrained to 50% of the width of the parent.
Then you set the white space back to normal, and make the second layer display:inline-block
so that these divs have to play by text alignment rules. Then you set both of them to vertical-align:middle;
Just one won't work because vertical align is relative to the baseline of the text, not the containing block element.
So in this way we have constrained ourselves to one line of "text", composed of two div elements both aligned such their middle is at the text baseline, and ensured that their size must be no more than 50% of the parent container.
EDIT: I discovered after little more playing that you need to add some max-width:100% to keep the image from pushing the text out the right hand side.
EDIT 2: I should have mentioned that this requires IE-8 standards mode, added meta-equiv to tell IE-8 to behave itself, but giving a proper doctype or sending an http response header can achieve the same thing google IE8 standards mode for all that stuff.
<html >
<head>
<title>Test</title>
<meta http-equiv="X-UA-Compatible" content="IE=8" />
<style type="text/css">
.wrapper1 {
white-space:nowrap;
max-width:50%;
}
.wrapper2 {
white-space:normal;
display:inline-block;
vertical-align:middle;
max-width:100%;
}
.variable-img {
max-width:100%;
}
</style>
</head>
<body>
<div class="wrapper1">
<div class="wrapper2">
<img class="variable-img" src="test.png">
</div>
<div class="wrapper2">
<div id="box">
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum</div>
</div>
</div>
</body>
</html>