I have two elements side-by-side. Element 2 is smaller than Element 1. Both elements do not have a fixed height. I need to vertically center Element 2. How do I achieve this using CSS?
Edited:
This is what I have so far:
<div id="container" style="width: 100%;">
<div id="img1" style="float: left;">
<img src="image1.jpg".../>
</div>
<div id="img2" style="float: right;">
<img src="image2.jpg".../>
</div>
</div>
img1's height will always be greater than img2's height. I want img2 to be aligned vertically-center. Hopefully this clarifies what I am trying to accomplish.
The most straightforward and clean way to do it is to use display: table
and vertical-align. However, IIRC (it's been a while since I was up on browser compatibility issues) support for display: table
and friends is absent from ... some common-then version of IE, perhaps? Anyway, adding other rules to make an adequate fallback if the display: table
is ignored might be good.
<div id="container" style="display: table;">
<div id="div1" style="display: table-cell; vertical-align: middle;">
<img id="img1" src="image1.jpg" />
</div>
<div id="div2" style="display: table-cell; vertical-align: middle;">
<img id="img2" src="image2.jpg" />
</div>
</div>
(Of course the styles ought to be in a stylesheet; this is just matching your original example and not knowing the use case.)
The display
values table
, table-row
, and table-cell
basically perform exactly like HTML table
, tr
, and td
, but you are permitted to omit any of them (as I do here, using table-cell
s directly within table
s) and the layout engine will do the sensible thing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With