Search code examples
htmlcssbackground-image

Fit background image on div element with dynamic width


How to fit the div to 100% of it's container and maintain the same background image if we specified a background-position for that image?

CSS

#content {
    position: relative;
    max-width: 50%;
    height: 0;
    padding: 0 0 50% 0;
}
.icon-1 {
   position: absolute;
   top: 0;
   left: 0;
   width: 100%;
   height: 100%; 
   background: url( "/path/to/my/image.png" ) no-repeat -50px -50px;
  /*
  -50px -50px is corresponding to letter "D" in the image
  */
 }

The HTML

<div id='content'>
   <div class='icon-1'>
   </div>
</div>

The idea is to use a single file for some icon-like images (to visually represent each shopping category)

#content {
    position: relative;
    max-width: 50%;
    height: 0;
    margin: 0 auto 0 auto;
    padding: 0 0 50% 0;
}
.icon-1 {
   position: absolute;
   top: 0;
   left: 0;
   width: 100%;
   height: 100%; 
   background: url( "https://i.sstatic.net/4FzW2.png" ) no-repeat -50px -50px #aa0000;
  /*
  -50px -50px is corresponding to letter "D" in the image
  */
 }
<div id='content'>
   <div class='icon-1'>
   </div>
</div>

test image


Solution

  • You simply need to adjust the value of background. In your case, it should be 2x the size of the red box then adjust the position to bottom/right to have the D and top/left for the A and so on:

    #content {
      position: relative;
      max-width: 50%;
      height: 0;
      margin: 0 auto 0 auto;
      padding: 0 0 50% 0;
    }
    
    .icon-1 {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: url("https://i.sstatic.net/4FzW2.png") bottom right/200% 200% no-repeat;
    }
    <div id='content'>
      <div class='icon-1'>
      </div>
    </div>