0

I'm looking to have a 100% width image that displays inside a 16:9 ratio frame. The image should be centered within the frame and be responsive to screen resizing. Ideally, I would like to be able to do this with just CSS.

stroz
  • 1,890
  • 1
  • 16
  • 28

2 Answers2

0

Combining multiple SO answers, I was able to get it working using the following styles. The dimensions of frame are set as 100% width in .grid_6 and 56.25% height in .grid_6::after.

JS Fiddle: http://jsfiddle.net/stroz/fz2ez4uv/2/

HTML

<div class="thumb grid_6">
    <img src="http://placekitten.com/g/200/300" />
</div>

CSS

.grid_6 {
    width: 100%;
    overflow:hidden;
    position:relative;
}

.grid_6::after {
  padding-top: 56.25%; /* percentage of containing block _width_ */
  display: block;
  content: '';
}

.thumb img {
    display: block;
    width:100%;
    height:auto;
    position: absolute;
    top: -9999px;
    bottom: -9999px;
    left: -9999px;
    right: -9999px;
    margin: auto;
}

This solution combines methods outlined in these questions:

How to keep image aspect ratio inside a %width div?

Scale a div to fit in window but preserve aspect ratio

Community
  • 1
  • 1
stroz
  • 1,890
  • 1
  • 16
  • 28
0
.aspect { max-width: 100%; }
.aspect.dims16by9:before {
    content: '';
    display: block;
    width: 100%;
    padding-bottom: 56.25%; // 9/16
}
.aspect.dims4by3:before {
    content: '';
    display: block;
    width: 100%;
    padding-bottom: 75%; // 9/16
}

less mixin:

.aspectRatio(@widthAspect, @heightAspect) {
    @aspect: @heightAspect/@widthAspect * 100;
    max-width: 100%;

    &:before {
        content: '';
        display: block;
        width: 100%;
        padding-bottom: ~"@{aspect}%";
    }
}
Todd
  • 5,314
  • 3
  • 28
  • 45