Eric Eric - 3 months ago 11
CSS Question

Responsive layout - 4 sprites in a row, stretch/shrink to enclosure

I have 4 images and I'd like them to dynamically resize so they are always shown on one row with no gaps (that is, all 4 should always take up the full width of the enclosing DIV, regardless of how wide/narrow that DIV is).

Example code is here: http://codepen.io/pnoeric/pen/YGXOJb



.enclosure {
width: 532px; // arbitrary size - could be '100%' or '312px'
border: solid 2px red;
}
.sprite {
float: left;
width: 100px;
height: 30px;
}
/*
all sample images are 100x30
*/

.s1 {
background: url('https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTqwGCIaDwDynzLuM-YQaf6hbKOrPZ7X5kPbBXeG2xONmjg7wQAhw');
}
.s2 {
background: url('https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSSZ7q4ghxvj5iOSHtJCf0UHMbh_JFnLLJEKH4kqtDfcB70-1T_jA');
}
.s3 {
background: url('https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTjcLooOn0vKrelH5ecjYIFYSEKl2AE64VqoLcxtyBRnzESArTKFg');
}
.s4 {
background: url('https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTTorTZRr54yI3fsL-X6xtXfnkbtATCqWF_ZIWF9g4QvsPg5g09');
}

<h3>
THE GOAL: get each image below to stretch (or shrink) to
fill enclosure with no gaps... example here should have
each image stretch to 133px (532 / 4)
</h3>

<div class='enclosure'>
<div class='sprite s1'></div>
<div class='sprite s2'></div>
<div class='sprite s3'></div>
<div class='sprite s4'></div>
</div>





Is this possible? Or do I need to go back to tags and some kind of table?

Answer

When you want responsiveness, you should use percentage for the sizes.

.enclosure {
  width:500px;    // arbitrary size - could be '100%'
  border:solid 2px red;
}

.sprite {
  float:left;
  width:25%;
  height:30px;
  background-repeat:no-repeat !important;
  background-size: 100% 100% !important; /* you can use other options like cover */
}

/* all sample sprites are 100x30 images -- yes in the real code I actually pull them all from one background image, like real CSS sprites :-) */

.s1 { background: url('https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTqwGCIaDwDynzLuM-YQaf6hbKOrPZ7X5kPbBXeG2xONmjg7wQAhw'); }

.s2 { background:url('https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSSZ7q4ghxvj5iOSHtJCf0UHMbh_JFnLLJEKH4kqtDfcB70-1T_jA'); }

.s3 { background:url('https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTjcLooOn0vKrelH5ecjYIFYSEKl2AE64VqoLcxtyBRnzESArTKFg'); }

.s4 { background:url('https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTTorTZRr54yI3fsL-X6xtXfnkbtATCqWF_ZIWF9g4QvsPg5g09'); }
<div class='enclosure'>
  <div class='sprite s1'></div>
  <div class='sprite s2'></div>
  <div class='sprite s3'></div>
  <div class='sprite s4'></div>
</div>