Set the dimensions of the style div to match those of the image it contains

I am struggling to position a div or button so that it matches the dimensions of the image it contains, without exceeding the dimensions of the parent div(s).

Despite my efforts, I can't seem to get it right for both vertical and horizontal images. When I adjust the box for the horizontal image, the vertical one ends up overflowing at the bottom.

It's important to note that I have no control over the image itself as it may come in various aspect ratios and sizes. Additionally, the outermost div is determined by the user's window size.

function log() {
  console.log("Click!");
}
.container {
  height: 100%;
  width: 50%;
  display: block;
  padding: 0;
  background-color: lightgreen;
}

.zoom {
  display: block;
  max-height: max-content;
  max-width: max-content;
  height: 100%;
  width: 100%;
  margin: auto;
  background-color: aqua;
}

img {
  max-height: 100%;
  max-width: 100%;
  height: 100%;
  width: 100%;
  object-fit: contain;
}
<div style="height: 500px; display: flex; flex-direction: row; overflow: scroll; background-color: lightgray">
  <div class="container">
    <div class="zoom" onclick="log()">
      <img src="https://upload.wikimedia.org/wikipedia/commons/0/0f/Eiffel_Tower_Vertical.JPG" />
    </div>
  </div>
  <div class="container">
    <div class="zoom" onclick="log()">
      <img src="https://upload.wikimedia.org/wikipedia/commons/f/f6/Eiffel_tower_at_dawn_horizontal.jpg" />
    </div>
  </div>
</div>

Desired outcome:

In this scenario, I have two divs - container (green) and zoom (aqua). The size of the container is dependent on the user's window size and the zoom div contains an image that should fill as much of the container's area while maintaining its aspect ratio and being centered. This might result in some empty space around the sides or top/bottom of the picture based on the image's aspect ratio. I need the size and position of the zoom div to match exactly with the image as an event handler is attached to it.

The green section represents the container while the aqua section displays either a portrait or landscape image. The goal is to ensure that the dimensions and positioning of zoom align perfectly with the image.

https://i.sstatic.net/1C0m1.png

Answer №1

const btn = document.querySelector("button");
const images = document.querySelectorAll("img");

btn.addEventListener("click", function (event) {
  for (let j = 0; j < images.length; j ++) {
    images[j].classList.toggle("hidden");
  }
});
div{
  display: flex;
  flex-flow: row nowrap;
  justify-content: center;
  align-content: center;
  align-items: center;
  outline: 1px dashed blue;
  height: 100vh;
  width: 100%;
}

img{
  max-width: 100%;
  width: auto;
  max-height: 100%;
  height: auto;
  flex: 1 1 auto;
}

.hidden{
  display:none;
}
<button>toggle</button>
<div>
<img src="https://www.example.com/image1.jpg" alt="pic1">

<img src="https://www.example.com/image2.jpg" alt="pic2" class="hidden">

</div>

Answer №2

Utilizing background-image in CSS can present a great opportunity! CSS offers various properties like background-repeat, background-size, and background-position that can assist us in incorporating images within a box. The beauty of it is that if we wish to switch images using JS, all we need to do is assign a new value to style.backgroundImage.

Feel free to experiment with adjusting the picsum image size or other properties related to the background- properties when you execute the provided code snippet!

#img-container-wide {
  width: 200px;
  height: 100px;
  border: 1px solid green;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: url("https://picsum.photos/200/300");
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center;
}

#img-container-tall {
  width: 100px;
  height: 200px;
  border: 1px solid blue;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: url("https://picsum.photos/200/300");
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center;
}
<div id="img-container-wide"></div>
<div id="img-container-tall"></div>

Answer №3

The implementation using flex results in the image shifting between center and left alignment when resizing the browser window, with the right image failing to be centered properly in Safari 16.2. To address this, the CSS below ensures that .zoom is centered both vertically and horizontally within .container, maintaining the image's aspect ratio regardless of window size:

.outer-wrapper {
  min-height: 100%;
  display: flex;
  flex-direction: row;
}

.container {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.zoom {
  height: fit-content;
  width: fit-content;
}

img {
  max-width: 100%;
  max-height: 100%;
  display: block;
}

To accommodate varying image sizes, JS has been included to fetch random images dynamically for demonstration purposes:

/* For demo only */
let img_one = document.getElementById("img-1");
let img_two = document.getElementById("img-2");

function changeImages() {
  setImage(img_one, 800, 1200);
  setImage(img_two, 1800, 800);
}

function setImage(img, x, y) {
  img.setAttribute("src", `https://picsum.photos/${x-randomInt(50,400)}/${y-randomInt(50,400)}`);
}

function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min)
}
/* For demo only */

.outer-wrapper.demo {
  height: 300px;
  margin: 0;
  padding: 0;
  background-color: lightgray;
}

.container.demo {
  border: solid 1px #000;
  background-color: lightgreen;
}

.zoom.demo {
  background-color: aqua;
}


/* Required */

.outer-wrapper {
  min-height: 100%;
  display: flex;
  flex-direction: row;
}

.container {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.zoom {
  height: fit-content;
  width: fit-content;
}

img {
  max-width: 100%;
  max-height: 100%;
  display: block;
}
Click the button below to update images <button onclick="changeImages()">
  Update Images
</button>

<div class="outer-wrapper demo">
  <div class="container demo">
    <div class="zoom demo">
      <img id="img-1" />
    </div>
  </div>
  <div class="container demo">
    <div class="zoom demo">
      <img id="img-2" />
    </div>
  </div>
</div>

Answer №4

To eliminate the blank space beneath the image, consider setting either img { display: block; } or img { vertical-align: bottom; }. It's important to note that this whitespace is not due to padding. By default, images have a display of inline, which can result in unexpected behavior such as extra whitespace below the image for descenders (the parts of letters that extend below the baseline, like 'y' and 'p').

Answer №5

Through some experimentation, I have successfully created a working example using display: flex, with guidance from @DataMoose:

function print() {
 console.log("Clicked!");
}
.container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  height: 100%;
  width: 50%;
  padding: 0;
  background-color: lightgreen;
}

.zoom {
  max-height: 100%;
  max-width: 100%;
  margin: 0 auto;
 
  background-color: aqua;
}

img {
  display: block;
  max-width: 100%;
  max-height: 100%;
}
<div style="height: 300px; display: flex; flex-direction: row; overflow: scroll; background-color: lightgray">
  <div class="container">
    <div class="zoom" onclick="print()">
      <img src="https://upload.wikimedia.org/wikipedia/commons/0/0f/Eiffel_Tower_Vertical.JPG" />
    </div>
  </div>
  <div class="container">
    <div class="zoom" onclick="print()">
      <img src="https://upload.wikimedia.org/wikipedia/commons/f/f6/Eiffel_tower_at_dawn_horizontal.jpg" />
    </div>
  </div>
</div>

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

Tips for retaining user input in an input box using HTML and AngularJS

Is there a way to retain a user's input in an input box? This is the current code snippet: <input type="text" ng-model="userText" placeholder="Enter text here"> However, I am looking for a solution that will allow the entered text to persist ...

The Mystery of jQuery Isotope Plugin: Why Can't I Add "display:none" Inline?

I'm currently in the process of integrating Isotope into my latest Wordpress theme. However, I've encountered an issue where it's not appearing on the page due to some external factor adding an inline style (display:none) to the main isotope ...

Creating a dropdown menu with HTML and CSS is causing me a major migraine

<div class="fbtop"> <img src="https://static.solidshops.com/1441/files/Logo-site.png" title="Pieke Wieke" alt="Pieke Wieke"> <h2 class="title">Handcrafted with love</h2> <ul class="dropdown"> <li> <a hre ...

Retrieve the concealed division element's HTML content along with its formatting

Help needed with appending a hidden div with its styles intact. Despite using the code provided below, the appended div does not retain its styles. Any suggestions for an alternative method? var warningMessage = $('#warningDiv').html() fun ...

What methods can be used to troubleshoot an issue of an AngularJS function not being called

I am facing an issue with a dynamic table I have created. The rows and action buttons are generated dynamically when the user clicks on the Devices accordion. However, there seems to be a problem with the function expandCollapseCurrent(). Whenever the use ...

The onchange function in JavaScript is malfunctioning

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Product page</title> <!-- Fonts -- ...

Tips for accessing the HTML code of a TextBox in JavaScript while utilizing HTMLEditorExtender

Currently, I am utilizing the HTMLEditorExtender ajax tool on my website. The data is being saved in HTML format into the database and then retrieved within my project without any issues. However, there is a setback that I have encountered... When attemp ...

Encountered a 404 error when attempting to deploy create-react-app due to failed resource loading

Any assistance would be greatly appreciated. Thank you! Although my website runs smoothly locally, I am encountering issues when trying to deploy it in a production environment. Upon executing npm run deploy, the expected outcome is an automatic build for ...

Combining several markdown files into a unified HTML document

Is there a way to merge multiple .md files into a single HTML file? I know that Pandoc can convert .md to HTML, but I'm unsure if it's capable of converting multiple files at once. Would I need to create a program to manipulate the tool in orde ...

Efficiently finding the right section by utilizing the hamburger menu, ensuring the menu does not obscure the text

In my bootstrap application, I am facing an issue with the hamburger menu. To understand the problem better, you will need both a laptop and a mobile device to follow these steps: 1: Visit on your desktop computer. 2: Scroll up and down the page to see ...

html Comparison of Documents

My goal is to compare HTML documents to see if they have the same tags in the same arrangement, regardless of different inner text and attribute values. I am only interested in comparing the general tag structure, such as: <html> <head> </h ...

Mobile view doesn't quite center using flexbox, even though it works fine on desktop

Utilizing flexbox, the two distinct sentences that form the content of the page are centered. However, upon viewing the website on my mobile phone, the second sentence appears aligned to the left side. Here's how the site appears on a phone I've ...

The issue with the CSS background gradient is that it fails to completely cover the entire

Despite attempting several solutions recommended in similar questions, I am still unable to resolve the issue. Using the CSS background gradient generator at Ultimate CSS, I found that the gradient only extends halfway down the page on www.ncentertain.com ...

I'm curious if there is a contemporary alternative to "Deep Zoom Composer" in Silverlight that enables the creation of panoramic images by stitching multiple images together

There was a time when Silverlight offered a feature known as "deep zoom", which cleverly adjusted bandwidth usage as the user zoomed in and out. Recently, I discovered a unique application for this technology - by incorporating images taken from a hot air ...

Error in thread : TagNameUnexpectedException

I encountered an issue while trying to find a dropdown using Select: An error occurred: Exception in thread "main" org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "input" Even when attempting to use ...

Troubleshoot: CSS class H2 style is not displaying correctly

I have the following code in my .css file: h2.spielbox { margin-bottom:80px; color:#f00; } a.spielbox { text-decoration:none; background-color:#aff; } However, in my html file, the h2 style is not ...

Activate event starting from parent and ascending through child nodes

When I have a table inside a <div class="timely"></div>, and within that table is a <th class="prev"><i>previous</i></th>, Chrome developer tools show an event listener on the <th>. However, Firefox developer tools ...

There seems to be an issue with ReactDOM.createPortal() generating redundant empty divs in next.js with TypeScript

This is the backdrop component in TypeScript: interface BacdropProps { open?: string; onClick: () => void; } const Backdrop: React.FC<BacdropProps> = (props) => { let container: HTMLDivElement | null = null; if (typeof window !== " ...

Tips for transferring information between two HTML pages

Looking for some advice here. I'm in the process of creating a website for my record store using HTML5. On one page (store.html), I plan to showcase all the albums with a Buy Now button below each album that links to buy.html <div class="item got ...

CSS :hover problem, text appearing unexpectedly

I'm currently working on designing a logo that displays hidden text when hovered over, providing instructions to users. However, I've encountered an issue where the hidden text reveals itself even before the logo is hovered over. This is frustrat ...