CSS Tutorials

Making Media Flexible

Images, videos, and iframes often break layouts on smaller screens. The trick is to give them a fluid container that maintains the aspect ratio.

HTML Structure

<div class="responsive-media">
  <iframe src="https://www.youtube.com/embed/dQw4w9WgXcQ"
          title="YouTube video"
          allowfullscreen></iframe>
</div>

<div class="responsive-media">
  <img src="/assets/img/sample.jpg" alt="Sample">
</div>

Responsive CSS

.responsive-media{
  position:relative;
  width:100%;
  height:0;
  padding-bottom:56.25%; /* 16:9 */
}
.responsive-media iframe,
.responsive-media img,
.responsive-media video{
  position:absolute;
  top:0;
  left:0;
  width:100%;
  height:100%;
  object-fit:cover;
}

The padding-bottom value creates a box with the desired aspect ratio. Adjust it for 4:3 (75%) or other ratios.

Live Demo

Random Landscape

Further Reading