Skip to content

Instantly share code, notes, and snippets.

@benji1304
Created October 1, 2017 21:03
Show Gist options
  • Save benji1304/53e3a5ca8dd26f2d010df94be5ef2688 to your computer and use it in GitHub Desktop.
Save benji1304/53e3a5ca8dd26f2d010df94be5ef2688 to your computer and use it in GitHub Desktop.
.container {
width: 50%;
height: 200px;
overflow: hidden;
}
.container img {
max-width: 100%;
height: auto;
display: block;
}
@benji1304
Copy link
Author

In the example above, .container represents a container div. It is set to a width of 50% (half of the browser's width, in this example) and a height of 200 pixels. Setting overflow to hidden ensures that any content with dimensions larger than the container will be hidden from view.

The second CSS rule ensures that images scale with the width of the container. The height property is set to auto, meaning an image's height will automatically scale proportionally with the width. Finally, the last line will display images as block level elements (rather than inline-block, their default state). This will prevent images from attempting to align with other content on the page (like text), which can add unintended margin to the images.

@benji1304
Copy link
Author

Note: The example above scales the width of an image (or video) to the width of a container. If the image is larger than the container, the vertical portion of the image will overflow and will not display. To swap this behavior, you can set max-height to 100% and width to auto (essentially swapping the values). This will scale the height of the image with the height of the container instead. If the image is larger than the container, the horizontal portion of the image will overflow and not display.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment