I want my image on the left to be cropped but I want my content to
dictate the overal height of the .example
element.
When using an img
, what first comes to mind is object-fit
, though since it has not the best browser support, here is one that has, making use of background-image
.
Generally, when using background-image
, one set the image source in the external CSS, though sometimes one want to set it in the markup, like one does when using an img
.
An often overlooked possibility when this is needed, is to simply use the style
attribute, which is no more complicated than the src
attribute on the img
, where one can set the source in markup like this: style="background-image: url(...)"
I also used flex-basis: calc(60% - 30px)
. This overcome 2 bugs in IE, where one can't use calc
in shorthand flex
and the border-box
issue to have padding inlcuded in the set width.
Stack snippet
.example {
max-width: 600px;
}
.flex-row {
display: flex;
flex-wrap: wrap;
}
.flex-row .image {
flex-grow: 1;
background-position: center;
background-size: cover;
}
.flex-row .content {
flex-basis: calc(60% - 30px);
padding: 15px;
background: #b7bdbb;
}
<div class="example">
<div class="flex-row">
<div class="col image" style="background-image: url(https://via.placeholder.com/500x265)">
</div>
<div class="col content">
some content
</div>
</div>
</div>
If you still need (or have to) use an img
, here is one sample that work cross browsers.
Since several browsers, i.a. Safari (appears to be fixed from v. 11 though) and IE, have issues with Flexbox and absolute positioned flex items, I here make use of transform: translate
to provide a solution to center the image.
Stack snippet
.example {
max-width: 600px;
}
.flex-row {
display: flex;
flex-wrap: wrap;
}
.flex-row .image {
flex-grow: 1;
position: relative;
overflow: hidden;
}
.flex-row .image img {
position: absolute;
left: 0;
top: 50%;
width: 100%;
transform: translateY(-50%);
}
.flex-row .content {
flex-basis: calc(60% - 30px);
padding: 15px;
background: #b7bdbb;
}
<div class="example">
<div class="flex-row">
<div class="col image">
<img src="https://via.placeholder.com/500x265)" alt="">
</div>
<div class="col content">
some content
</div>
</div>
</div>