Making picture fit inside of container

Hi so I am trying to make a picture fit inside of my HTML-container. But I don’t quite know what command I should use to make it fit the conatainer’s size.

Looks like this now:

Also, I want to know if it is another way to(besides making it fit) dragging it around. So it keeps the same size as in the picture but dragg it down a bit so the top of the glass gets lower down inside of the container?

Most of the time you would add a width of 100%.

There is a small lesson on FCC: https://www.freecodecamp.org/learn/responsive-web-design/responsive-web-design-principles/make-an-image-responsive

W3schools some more stuff: Responsive Web Design Images

For your specific question, you can add a padding.

But actually pixel-perfecting paddings is normally not a good idea, because it probably breaks on different devices.

Hmm how can I alter my code to make that happen. Looks like this now:

body {
    background-image: url(images/), linear-gradient(blue, white);
    height: 100vh;
    background-size: cover;
    background-position: center;
    }

    .Box1 {
        background-color: gold;
        background-image: url(images/pradnyal-gandhi-1MqDCpA-2hU-unsplash-flyingbeer.jpg), linear-gradient(45deg, white, gold, black, brown);
        background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    position: relative;
        padding: 5%;
        height: 300px;
        margin: 10%;
        margin-top: 7%;
        box-shadow: black 2px 2px 100px;
        z-index: 10;
      }

The problem with responsively resizing divs with background-images is that you can’t set a fixed height, you instead want to have a fixed aspect-ratio (like 4:3 for an image that is 400px wide and 300px high). I found this neat trick a while ago on w3schools: How To - Aspect Ratio / Height Equal to Width

How it works:

  • a container div with a padding-top:100% (for a square image) or padding-top:50% (for an image with aspect-ratio 2:1)
  • container is position:relative
  • within the container, a div that holds the background-image, set to position:absolute.

Experiment with this HTML:

<body>
    <div class="container">
        <div class="bg-image"></div>
    </div>
</body>

And this CSS:

.container {
    width:50%;
    margin:0 auto;
    position:relative;
    padding-top:75%;
}
.bg-image {
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:100%;
    background-image:url('https://upload.wikimedia.org/wikipedia/commons/thumb/d/de/Aspect-ratio-4x3.svg/1007px-Aspect-ratio-4x3.svg.png');
    background-repeat:no-repeat;
    background-size:contain;
}

The image will always be perfectly sized, and at the same time responsively grow and shrink.

1 Like