How to stop an image changing the size of an container

I am in my first year of software development, learning bootstrap.

I try to add an image that is bigger then 400*200 but it’s making the container bigger and out of shape, how do I lock the container.

Thanks.


Hi there kylegilmartin5,

before you start using Bootstrap, if ever, you
really must learn the basics of Vanilla CSS. :winky:

<!DOCTYPE HTML>
<html lang="en">
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">

<title>untitled document</title>

<!--<link rel="stylesheet" href="screen.css" media="screen">-->

<style media="screen">
body {
    background-color: #f9f9f9;
    font: normal 1em / 1.5em BlinkMacSystemFont, -apple-system, 'Segoe UI', roboto, helvetica, arial, sans-serif;
 }

#container {
    max-width: 25em;
    border: 0.25em solid #000;
    margin: 1em auto;
 }

#container img {
    display: block;
    width: 100%;
    height: auto;
 }
</style>

</head>
<body> 

 <div id="container">
  <img src="https://via.placeholder.com/1200x600"" width="1200" height="600" alt="Big Picture">
 </div>

</body>
</html>

coothead

I know ya, its aside project my professor wants us to try.

tried your code with a bigger img and the container gets bigger

Do you really think that I would give you some
simple,basic HTML and CSS if it did not work?

Here is what it looks like at 1100px…

1100

…and here is what it looks like at 300px…

300

coothead

see how the container get bigger as I add an image that is bigger then 400/200, how do i lock the container to were if i add an image that is bigger then 400/200 the image shrinks to fit the container

thanks

If you have the container for the image set at 400px x 200px then the only way to make an image fit that container would be to use object-fit:cover on the image and set the image to width and height of 100%.

Object-fit is not supported in IE but supported in other modern browsers.

Be aware that you cannot simply shrink an image to fit the height and width of an element if that element is not the same aspect ratio as the image. Otherwise the image will be stretched or squashed. Object-fit gets around this by expanding the width and height of the image until both dimensions cover the area required. This means the image will be cropped to fit but will still maintain its aspect ratio. It’s the same as using background-size:cover when using background images.

1 Like

Thanks Paul will try that

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.