title: image with border inside fixed width container
body: <p>I have a fixed width container (div) and an image inside, this image should fit the container width but having a margin, like this:</p>
  
  <p><a href="https://i.stack.imgur.com/q5PM6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/q5PM6.png" alt="enter image description here"></a></p>
  
  <p>I tried adding a padding to container, it makes container bigger.</p>
  
  <p>My second attempt was adding a margin to the image, but it makes it go outside the container.</p>
  
  <p>Both attempts are in this snippet:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>$('.result1').html('div is ' + $('.test1').width() + ' and image is ' + $('.test1 img').width());
  $('.result2').html('div is ' + $('.test2').width() + ' and image is ' + $('.test2 img').width());</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>div{
    width: 300px;
    background-color: #999;
  }
  img{
    background-color: #FFF;
    width: 100%;
  }
  .test1{
    padding:10px;
  }
  .test2 img{
    margin:10px;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;
  &lt;div class='test1'&gt;
    &lt;img src='http://www.iconsdb.com/icons/preview/orange/stackoverflow-4-xxl.png' /&gt;
  &lt;/div&gt;
  &lt;div class='result1'&gt;&lt;/div&gt;
  &lt;div class='test2'&gt;
    &lt;img src='http://www.iconsdb.com/icons/preview/orange/stackoverflow-4-xxl.png' /&gt;
  &lt;/div&gt;
  &lt;div class='result2'&gt;&lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>