Dancer Dancer - 7 days ago 5
CSS Question

CSS: Positioning an IMG tag within a div with overflow

I am building a responsive website that contains a complex collapsible grid - which requires parts of large images to be displayed within smaller fixed width divs - which will adjust in size based on media queries - overflows are hidden to give a masked effect.

I need to position the images to -


  • Left Top

  • Center Top

  • Left Top



Of course left top is standard browser behaviour - but I need best practice cross-device/browser solutions for center/top and left/top.

So for example - the following code structure -

<div style="width:100px; height:50px; overflow:hidden;">
<img src="http://i.guim.co.uk/static/w-620/h--/q-95/sys-images/Guardian/Pix/pictures/2014/9/24/1411574454561/03085543-87de-47ab-a4eb-58e7e39d022e-620x372.jpeg" style="width:620px; height:320px;">
</div>


How would I position the image tag Center-top or left-top

Answer

You can use absolute positioning with the properties top, bottom, left, right.

div {
  width: 200px;
  height: 100px;
  overflow: hidden;
  position: relative;
  margin: 10px;
  display: inline-block;
}
img[data-position] {
  position: absolute;
  border: 1px dotted red;
}
img[data-position*=top]    { top: 0;    }
img[data-position*=bottom] { bottom: 0; }
img[data-position*=left]   { left: 0;   }
img[data-position*=right]  { right: 0;  }
<div>
  <img src="http://i.stack.imgur.com/SyxjC.jpg" alt=""
       data-position="left top" width="620" height="320">
</div>
<div>
  <img src="http://i.stack.imgur.com/SyxjC.jpg"  alt=""
       data-position="right top" width="620" height="320">
</div>
<div>
  <img src="http://i.stack.imgur.com/SyxjC.jpg" alt=""
       data-position="left bottom" width="620" height="320">
</div>
<div>
  <img src="http://i.stack.imgur.com/SyxjC.jpg" alt=""
       data-position="right bottom" width="620" height="320">
</div>

Comments