0

I have a div with a fixed width (can change, but use fixed as an example). Text and Images will be displayed inside the div of varying sizes including 100% width. Images will have a 10px margin.

When I display a 100% width IMG, it spills outside of the div on the right side slightly. Is there a CSS way (or other?) to automatically have the IMG display within the div, accounting for the 10px margin on either side and NOT spill outside, while keeping the width:100% value?

I know I can workaround it by using a calculated amount, like width:94.5% (2nd image) for a 400px wide div container, but I would rather not have to do it this way as this results in recalculating every time the container width changes...maybe this is the best way after all?

Don't want to use overflow:hidden, as this will give a cut-off look...

Sample code:

<style>
.editor {
    width:400px;
    border-style:solid;
}
.editor img {
    object-fit: cover;
    object-position: top;
    display: block;
    margin:10px;
    border-style:solid;
}
</style>
<div class="editor"">
    <p>Spills over</p>
    <img style="width:100%" src="http://www.google.com.br/images/srpr/logo3w.png">
    <p>Looks right, but uses odd calculated width</p>
    <img style="width:94.5%" src="http://www.google.com.br/images/srpr/logo3w.png">
</div>
HDer
  • 385
  • 5
  • 17
  • Not sure what the point of using `object-fit` is supposed to be in that example? Sounds like you might want to look into https://developer.mozilla.org/en-US/docs/Web/CSS/calc() to specify the image width. – CBroe Jan 28 '21 at 11:42
  • Yes, I quickly came across the same solution of calculating the width as your link has suggested. style="width: calc(100% - 22px)" 10px margin on each side + 1px left border + 1px right border. – HDer Jan 28 '21 at 11:56

0 Answers0