Gelgamek Gelgamek - 26 days ago 6
CSS Question

Responsive img with flexbox

Hi and thanks to anyone replying to this post. I have wrapped an Img with an anchor tag and the img no longer shrinks as the page is resized. I know that flexbox only applies flex properties to child elements, so wrapping the img with an anchor would make it a grandchild. But even when applying flex to the anchor the image still fails to shrink.



.rightContent {
color: white;
padding: 20px;
display: flex;
flex-direction: row-reverse;
justify-content: space-between;
background: #375D81;
}

.leftContent {
color: white;
padding: 20px;
display: flex;
justify-content: space-between;
background: #183152;
}

<div class="rightContent">
<h3>Date Added: 11/4/2016</h3>
<p>dictum elit pretium. In sagittis euismod diam a pharetra. Nunc venenatis aliquet massa sed mollis. Nulla nec est metus. Aliquam in tortor </p>
<a href="https://color.adobe.com/explore/most-popular/?time=all">
<img src="http://placehold.it/350x150" alt="" /></a>
</div>

<div class="leftContent">
<h3>Date Added: 11/4/2016</h3>
<p>dictum elit pretium. In sagittis euismod diam a pharetra. Nunc venenatis aliquet massa sed mollis. Nulla nec est metus. Aliquam in tortor</p>
<a href="http://lorempixel.com/"></a><img class="right " src="http://placehold.it/350x150" alt="" />
</div>




Answer

The image is not shrinking as the image is not constrained to the flex-item a - just use this:

a img{
  width: 100%;
}

and now the img will respect the dimensions of a. See here for more info on how we restrict the dimensions of images without affecting the intrinsic aspect-ratio.

.rightContent {
    color: white;
    padding: 20px;
    display: flex;
    flex-direction: row-reverse;
    justify-content: space-between;
    background: #375D81;
}

.leftContent {
    color: white;
    padding: 20px;
    display: flex;
    justify-content: space-between;
    background: #183152;
}
a img{
  width: 100%;
}
<div class="rightContent">
        <h3>Date Added: 11/4/2016</h3>
        <p>dictum elit pretium. In sagittis euismod diam a pharetra. Nunc venenatis aliquet massa sed mollis. Nulla nec est metus. Aliquam in tortor </p>
        <a href="https://color.adobe.com/explore/most-popular/?time=all">
            <img src="http://placehold.it/350x150" alt="" /></a>
    </div>

    <div class="leftContent">
        <h3>Date Added: 11/4/2016</h3>
        <p>dictum elit pretium. In sagittis euismod diam a pharetra. Nunc venenatis aliquet massa sed mollis. Nulla nec est metus. Aliquam in tortor</p>
        <a href="http://lorempixel.com/"><img class="right " src="http://placehold.it/350x150" alt="" /></a>
    </div>

Comments