mgrowan mgrowan - 4 months ago 9
CSS Question

Stop an img with an explicit inline width being larger than the parent div

I have user generated content that needs to scale to fit in the parent container.
I don't have control of anything inside the div.



.container {
max-width: 300px !important;
border: 1px solid black;
}

<div class="container">
<p><img style="width: 800px;" src="http://placekitten.com/g/800/200"><br></p>

<p>
Other content
</p>
<p>
CSS IS AWESOME
</p>

</div>





How to I keep the content bound?

Answer

So you have to specify for all children at any level have max-height of 100% of parent element :)

.container {
  max-width: 300px;
  border: 1px solid black;
}
.container *{
  max-width:100%;
}
<div class="container">
    <p><img style="width: 800px;" src="http://placekitten.com/g/800/200"><br></p>
    
    <p>
    Other content
    </p>
    <p>
    CSS IS AWESOME
    </p>
    
</div>

And I'd suggest you get rid of !important if nothing else is modifying element so CSS name would be justified for word Cascading :)