What is the correct method in CSS to resize an image while maintaining its proportions within a div container?

I've been struggling to properly insert images into a <div> element on my website. I've experimented with various techniques, such as setting max-width and max-height to 100%, changing the display property of the parent element to flex, and trying different values for object-fit. Am I overlooking something important, or is it just not feasible to achieve this?

openModal();

function openModal() {
  modal.style.display = "flex";
  var t = setTimeout(transitionOpenModal, 30);
}

function transitionOpenModal() {
  modal.style.opacity = "1";
  modalContainer.style.transform = "scale(100%)";
  modalContainer.style.webkitTransform = "scale(1)";
}

function closeModal() {
  modalContainer.style.transform = "scale(0%)";
  modalContainer.style.webkitTransform = "scale(0)";
  modal.style.opacity = "0";
  var t = setTimeout(closeModalAfterTransition, 250);
}

function closeModalAfterTransition() {
  modal.style.display = "none";
}
/* MODAL DIALOG */

.modal {
  display: none;
  opacity: 0;
  position: fixed;
  z-index: 99;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  transition: opacity 0.25s;
  justify-content: center;
  align-items: center;
}

.modal-header {
  position: sticky;
  padding-bottom: 16px;
}

.modal-container {
  background-color: white;
  border-radius: 4px;
  margin-left: auto;
  margin-right: auto;
  padding: 16px;
  max-width: 80vw;
  max-height: 80vh;
  filter: drop-shadow(0 4px 4px rgba(0, 0, 0, 0.25));
  transform: scale(0%);
  -webkit-transform: scale(0);
  transition: transform 0.25s;
}

.modal-content {
  max-width: 100%;
  max-height: 100%;
}

img.modal-content-inner {
  max-width: 100%;
  max-height: auto;
  object-fit: contain;
}

.modal-header>h2 {
  display: inline;
}

.modal-close {
  float: right;
  font-size: 24px;
  font-weight: bold;
}

.modal-close:hover,
.modal-close:focus {
  text-decoration: none;
  cursor: pointer;
}
<div id="modal" class="modal">
  <div class="modal-container" id="modal-container">
    <div class="modal-header">
      <h2 id="modal-title">modal</h2>
      <span class="modal-close" id="modal-close">&times;</span>
    </div>
    <div class="modal-content" id="modal-content">
      <img src="https://via.placeholder.com/1920x1080.png">
      <!-- this is a test case, please try with multiple image sizes -->
    </div>
  </div>
</div>

Check out how it currently appears on my website.

Answer №1

Adjusting the max-width of the image to 100% will help in keeping it within the confines of the containing div. Below is a simplified version of the code snippet:

  .modal {
          /* display: none; */
          /* opacity: 0; */
          position: fixed;
          z-index: 99;
          left: 0;
          top: 0;
          width: 100%;
          height: 100%;
          overflow: hidden;
          background-color: rgba(0,0,0,0.5);
          backdrop-filter: blur(10px);
          -webkit-backdrop-filter: blur(10px);
          transition: opacity 0.25s;
          justify-content: center;
          align-items: center;
      }

      .modal-header {
          position: sticky;
          padding-bottom: 16px;
      }

      .modal-container {
          background-color: white;
          border-radius: 4px;
          margin-left: auto;
          margin-right: auto;
          padding: 16px;
          max-width: 80vw;
          /* max-height: 80vh; */
          filter: drop-shadow(0 4px 4px rgba(0,0,0,0.25));
          /* transform: scale(0%);
          -webkit-transform: scale(0);
          transition: transform 0.25s; */
      }

      .modal-content {
          width: 100%;
          height: 100%;
      }

      .modal-content > img {
          max-width: 100%;
      }

      .modal-header > h2 {
          display: inline;
      }

      .modal-close {
          float: right;
          font-size: 24px;
          font-weight: bold;
      }

      .modal-close:hover, .modal-close:focus {
          text-decoration: none;
          cursor: pointer;
      }
<div id="modal" class="modal">
      <div class="modal-container" id="modal-container">
        <div class="modal-header">
          <h2 id="modal-title">modal</h2>
          <span class="modal-close" id="modal-close">&times;</span>
        </div>
        <div class="modal-content" id="modal-content">
          <img src="https://via.placeholder.com/1920x1080.png">
        </div>
      </div>
    </div>

Answer №2

Discovered the solution independently - it seems that I was able to simply adjust the max-width and max-height properties of the image directly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Integrating Labels on External Websites with ASP.NET

I have been developing a website that needs to display a counter on the home page. To accomplish this, I used an asp label that counts and displays the database records (e.g. 180000) with no issues at all. However, now I am facing a new challenge. I want ...

Pressing the button in the navigation bar results in an expansion of the navbar

Can someone help me figure out why my navbar's height is different from the example on this Bootstrap navigation bar snippet? Here's the code I used: https://www.w3schools.com/bootstrap4/tryit.asp?filename=trybs_navbar_form&stacked=h I copi ...

Differentiate input elements with custom styling

I'm experiencing an issue while trying to style a specific form field in Angular 7. The style doesn't seem to be applying properly. Below is my form structure: <ul> <li> <mat-form-field *ngIf="number"> <input ma ...

Ways to create a sequential appearance of elements through CSS animations

Can you help me achieve a wave effect for elements appearing one by one using CSS animation (jQuery)? Currently, all the elements show up at once and I want to create a wave-like motion. Any assistance would be greatly appreciated. $(window ...

Comparing Traditional Tables to Div Tables

Is this process: <table> <tr> <td>Hello</td> <td>World</td> </tr> </table> Achievable with the following code? <div> <div style="display: table-row;"> <di ...

associating the highlighted text with a specific attribute of the selectbox

Using my coding skills, I developed a small application that enables users to add text from a textarea to a div block. My goal is to prevent the appended text when the user clicks on the yellow div, and highlight the selected text properties (such as font ...

Designing HTML columns to adapt to different screen resolutions

Looking for a clever jQuery or CSS trick to dynamically adjust the number of columns in a website layout based on the size of the viewport. For instance, an iPhone display would have 1 column, while an 800x600 screen would have 2, and a 1024x768 screen wou ...

Bring in an SVG element from a separate document while retaining the CSS <style> details from the original source

Creating a number of SVG files can be made easier by keeping common symbols in one file and importing them into others. An effective method for achieving this is using the <use> element: <use href="common.svg#symbol1" /> However, th ...

Switch the CSS class when clicking on a responsive table within a table

I am looking to update the background color of a row within a table when a tr is clicked. Below is the code for the table: <div class="table-responsive"> <table class="table table-hover"> <thead> ...

Keep the table header in place while scrolling

I am currently working with Bootstrap V4 alpha 6 and Angular 5 to develop a table that includes a fixed header while scrolling. Unfortunately, I have been facing challenges in getting this functionality to work effectively. Note: The navbar is set to fixe ...

Ways to show dynamic text according to slider adjustments

I am struggling with adding an if condition to my form that includes a horizontal slider. My goal is to display text based on the position of the slider. Can someone offer some guidance on this, please? Here's my HTML code snippet: <form method=" ...

Error encountered while parsing Google Map link in Razor.Parse

Situation Within my application, I am utilizing Razor.Parse<>() to parse text, links, and tags to HTML. string Razor.Parse<TEmail>(string razorTemplate, TEmail model) where TEmail : BaseEmail I utilize the symbol '@' to extract dat ...

Tips for sorting through various elements or items

How can I improve my filtering function to select multiple items simultaneously, such as fruits and animals, or even 3+ items? Currently, it only allows selecting one item at a time. I attempted using , but it had bugs that displayed the text incorrectly. ...

Designs created using ASCII characters in HTML that are not under my control

Hey there! I've been attempting to incorporate some ASCII art onto a website that I don't have control over. When I input text into their editor, it is then enveloped in <p> tags which makes adding ASCII art quite challenging. Firstly, I ca ...

Make the checkbox font-weight bold when it is checked

Attempting to apply custom CSS to enhance the appearance of checkboxes using input and label elements. The goal is to make the font-weight bold when a user clicks on the checkbox, and then revert it back to regular if clicked again. Currently stuck on this ...

Prevent form submission when text fields are empty or dropdown selections are not made

I have a piece of code that is currently working with just one textbox input called 'departname'. However, I now need all input fields to be required and the dropdown menu for 'ACFTREG' (which is populated from a Sharepoint list) should ...

Develop a Vue component for a fixed sidebar navigation

I am in need of a vertical navigation bar positioned to the left of my app's layout, with the content extending across the right side. However, I am currently facing an issue where the navbar is pushing all the content downwards. How can I resolve thi ...

Adjust the size of the embedded iframe to match the dimensions of the containing div

Is there a method to resize the iframe embed code for a vine so that it fits within the boundaries of the enclosing div? The supplied embed code already includes sizing information as shown below: <iframe src="https://vine.co/v/iMJzrThFhDL/embed/simp ...

Unable to display the value of a server-side li element using JQuery

I am trying to retrieve values from a ul list that is populated from the database using server-side code. I want to display the li value in a jquery alert function, but it doesn't seem to be working as expected. Strangely, the same function works perf ...

How to dynamically inject HTML content from a child component into a different component using Angular 5

Is it possible to customize the content of a reusable header section based on the current route data in Angular? The header currently displays a title and description pulled from the route data property. My concern is how to dynamically inject different H ...