I have an image and text which I want to vertically align:
<div>
<img src="xyz.png" style="width:70%;">
<p>xyz</p>
</div>
The text floats around the image. The width of the is inlined because it's a wysiwyg content field and I have limited to no control over markup.
Now I thought about vertical alignment via flexbox:
div {
display: flex;
align-items: center;
}
Et voilà. It works but the percentage size of the image is not respected anymore. Why? Also, what is this new image size based on? It's not the percentage but also not the original size.
.original {
float: left;
}
img {
float: left;
padding: 10px;
}
.vAlign {
display: flex;
align-items: center;
}
<h1>Original Markup</h1>
<div class="original">
<img src="http://via.placeholder.com/350x150" style="width:70%;">
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd </p>
</div>
<h1>verticalign (But wrong img Size)</h1>
<div class="vAlign">
<img src="http://via.placeholder.com/350x150" style="width:70%;">
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam </p>
</div>
An initial setting of a flex container is flex-shrink: 1
. This means that flex items are permitted to shrink in order to avoid overflowing the container. Disable flex-shrink
.
.original {
float: left;
}
img {
float:left;
padding: 10px;
}
.vAlign {
display: flex;
align-items: center;
}
img { flex-shrink: 0; } /* NEW */
<h1>Original Markup</h1>
<div class="original">
<img src="http://via.placeholder.com/350x150" style="width:70%;">
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd </p>
</div>
<h1>verticalign (But wrong img Size)</h1>
<div class="vAlign">
<img src="http://via.placeholder.com/350x150" style="width:70%;">
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam </p>
</div>
ALSO NOTE that float does not work in a flex container.