To fit an image (auto-resize) into a container, set max-width property of image to 100%.
img{ max-width: 100%; }
In this example below, you will see that even though we have given width to the parent container, image still overflows.
HTML
<div class="container"> <img src="book.jpg"> <div class="container-text"> <h2>This is DIV TEXT</h2> <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Doloribus accusamus suscipit, voluptatem blanditiis repre iure ullam maxime dolores, delectus natus dolorem deleniti </p> </div> </div>
CSS
body{ margin: 0; padding: 0; box-sizing: border-box; } .container{ width: 450px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: #f5f5dc; } h2{ margin: 0; } .container-text{ padding: 15px; }
To fit the image into div container, apply the same CSS code mentioned above.
CSS
body{ margin: 0; padding: 0; box-sizing: border-box; } .container{ width: 450px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: #f5f5dc; } img{ max-width: 100%; } h2{ margin: 0; } .container-text{ padding: 15px; }