DEV Community

Cover image for How to scale an image inside of a div
BigCityC
BigCityC

Posted on

How to scale an image inside of a div

Here is a basic react app, using styled components.
I have set up an example of a div with an image inside of it.

If you open the codesandbox and try using the slider to resize the browser, you can see two things.

  1. The image remains the same size.
  2. The image β€œleaks” out of the div that it is a child of.
import styled from "styled-components";
import Laptop from "./laptop.png";

const Container = styled.div`
  border: 1px solid red;
`;

const Img = styled.img.attrs({
  src: `${Laptop}`
})``;

export default function App() {
  return (
    <Container>
      <Img />
    </Container>
  );
}
Enter fullscreen mode Exit fullscreen mode

codesandbox: https://codesandbox.io/s/scaling-images-1-kc05z

There are two things we need to add to the image if we want it to scale with its parent.

height: auto
max-width: 100%;
Enter fullscreen mode Exit fullscreen mode

height: auto
This allows the image to automatically adjust its height to allow the content to be displayed correctly.

max-width: 100%
This sets the width of the image so that the image will scale down if it has to, but never scale up to be larger than its original size.

NOTE: Using width: 100% instead will allow the image to be scaled up larger than its original size, in order to fit the full width of the div it is inside of. Most cases, it is better to use max-width.

Below is the same code with the solution. You can see from the demo that the image has resized correctly.

import styled from "styled-components";
import Laptop from "./laptop.png";

const Container = styled.div`
  border: 1px solid red;
`;

const Img = styled.img.attrs({
  src: `${Laptop}`
})`
  height: auto;
  max-width: 100%;
`;

export default function App() {
  return (
    <Container>
      <Img />
    </Container>
  );
}
Enter fullscreen mode Exit fullscreen mode

codesandbox: https://codesandbox.io/s/scaling-images-2-rxyx2

Top comments (0)