Tips on wrapping a div snugly around an image while also adjusting the image size to fit within the content area if it is larger than the content area

Currently working on developing an image viewer that has specific requirements to meet. Here they are:

  • The content area is defined as a grid-area.
  • If the image is larger than the content area, it must be contained without stretching.
  • If the image is smaller than the content area, it should be centered within the content area.
  • Ensure there is always a div tightly wrapping the image.

A visual representation has been sketched below to illustrate the desired behavior for both portrait (top row) and landscape (bottom row) images with the left column demonstrating the expected behavior when the image's resolution exceeds the content area.

Color coding is as follows:

  • White box: Content area.
  • Red box: Image.
  • Blue border: Wrapping div around the image.

https://i.sstatic.net/dzHpo.png

My primary approach thus far has involved absolutely positioning the wrapping div around the image, which generally works fine except when attempting to achieve resize-to-fit behavior. This often results in breaking the tightly wrapped div.

Although I can utilize JavaScript for this task, I would prefer to primarily rely on HTML and CSS due to laying a foundation for future expansions.

Answer №1

It is important to make sure that your div adjusts its size based on the content within it, such as an img. Avoid using absolute positioning in this case. If you are considering using grid, the example below demonstrates how to create a grid layout with a main section surrounded by 20px padding. Use the max value for the img to prevent it from exceeding the size of the grid box and center it within the grid:

const width = document.querySelector( '[name=width]' );
const height = document.querySelector( '[name=height]' );
const image = document.querySelector( 'img' );

function onchange(){
  
  image.src = `http://placehold.it/${width.value}x${height.value}`;
  image.style = '';
  
}

width.addEventListener( 'change', onchange );
height.addEventListener( 'change', onchange );

window.addEventListener( 'DOMContentLoaded', () => setTimeout( onchange, 100 ) );
body, html { height: 100%; }
body { padding: 0; margin: 0; }
main {
  display: grid;
  grid-template: "left top right" 20px "left main right" 1fr "left bottom right" 20px / 20px 1fr 20px;
  height: 100%;
}
main div {
  grid-area: main;
  border: 1px solid red;
  display: inline;
  align-self: center;
  justify-self: center;
}
main div img {
  max-width: 100%;
  max-height: 100%;
  display: block;
}
#inputs {
  position: absolute;
  top: 0;
  left: 0;
  transform: translateY(-100%);
  transition: transform .4s;
  width: 100%;
  padding: 10px;
  background: black;
  color: white;
}
body:hover #inputs {
  transform: translateY(0);
}
<main>
  <div>
    <img />
  </div>
</main>

<div id="inputs">
  <label>Width: <input name="width" value="200" type="number" /></label>
  <label>Height: <input name="height" value="200" type="number" /></label>
</div>

To enable testing of different image sizes, JavaScript has been included. The addition of img.style = '' triggers a CSS recalculation after inserting the new image, ensuring correct sizing upon load.

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

What is a way to adjust the width of fixed columns in a Bootstrap 4.0 responsive table?

I've been struggling to make this work despite following similar questions and answers. I attempted to adjust the column width by directly setting each one, but nothing seems to change! <thead style="white-space: nowrap"> ...

Encountering an Error while uploading to a NodeJS FTP server

I am utilizing the library https://github.com/mscdex/node-ftp to transfer a file to an FTP server. Below is the code snippet that I am using: const Client = require('ftp'); console.log('CONNECTING...') const c = new Client ...

Adjust the size of a div using absolute positioning

Can a div with absolute position be resized? I need this pink modal to maintain the same width as the input and resize accordingly. This modal will be utilized in a dropdown component, so it should resize along with the input. Moreover, is using absolute ...

Is there a way to establish a condition for an onSubmit event?

I have a form that I'm working on, and I would like for an error message to pop up upon the first onSubmit, and then function normally on subsequent submissions. Here is the current setup: const [submitting, setSubmitting] = useState(false); const ha ...

The CSS styling isn't being reflected on the button within the React component

Within my index.html file, where my React app is located, I have included a CSS stylesheet. Inside this stylesheet are the following CSS properties: #Webshop { background-color: white; height: 100%; width: 100%; } and #Webshop, button ...

Performing calculations within handsontable

Trying to figure out how to concatenate values from a handsontable grid, I stumbled upon some code on jsfiddle that caught my eye. Here is the link: http://jsfiddle.net/9onuhpn7/4/ The task at hand involves 3 columns A,B,C and an attempt to concatenate ...

Arrange CSS to distribute list items across two rows with an unlimited number of items

I need my list items to be arranged in 2 rows like the following: item 1 item 3 item 5 item 7 item 9 .... item 2 item 4 item 6 item 8 ...... My CSS skills are not great, so I am struggling to find a solution for this. I have at ...

Repairing the box nested within another box

I have a box within another box, but it's not aligned with the text. I want to center the box around the text so there is no extra space: http://jsfiddle.net/infoed/nvVBU/ (css included in the jsfiddle): <DOCTYPE! html> <html> <head&g ...

Send a JavaScript object to an MVC controller using an HTTP POST request

I'm encountering an issue while attempting to send a JavaScript object containing a string and a jstring to an MVC controller. Despite my code looking correct, I am receiving a null value in the controller. Any assistance would be greatly appreciated. ...

Tips for implementing $routeProvider's resolve function in electron-angular-boilerplate

I am encountering an issue with loading JSON data before entering the main controller in my project. Using this project as a template, I made alterations to only dist/app/home/home.js where the changes were implemented: angular.module('WellJournal&a ...

Using Javascript to retrieve text information through ajax and rendering it as a clickable link

Scenario: I need to display truncated text (e.g. My name is ...) in an HTML hyperlink, with the content fetched through an ajax call. Upon clicking the link, I want to load the full text into a modal dialog box using the same ajax call used for fetching t ...

What's the trick to aligning navigation items side by side?

I'm currently working with the code snippet below: header { height: 110px; width: 100%; margin-bottom: 130px; position: fixed; top: 0; z-index: 11; /*additional styling removed*/ } nav ul { list-style: none; paddin ...

Unlock the ability to retrieve the context element from a dynamically bound event within the event handler using jQuery

I have a chunk of HTML that gets inserted into the page and is connected to a click event handler. Here's an example in the code snippet below: var matchMore = $(".match-more-btn"); matchList.on("click", matchMore, function() { var self = $(this); ...

Selecting one, multiple, or all checkboxes and attempting to proceed by activating the button will not function as intended

The functionality of the "check all" / "uncheck all" button allows me to easily select or deselect all checkboxes within my form. The "proceed..." button should become active once one, multiple, or all checkboxes are checked. While this feature works smoo ...

Addressing the problem of refactoring in JavaScript when associating arguments with keys in MongoDB

I am facing a dilemma with two functions that are almost identical except for the value being set as indicated: function extracted_start(details, txt) { return FutureTasks.upsert({ number: details.number ...

Having issues updating table with Javascript after form submit in IE and Edge browsers

My current setup involves using Contact Form 7 in Wordpress to store data in a MySQL Database with Submit-Form. Now, I am working on reloading a table containing this data after the form submission. Here is the script I am currently using: /* FORM RELOAD ...

Updating a select menu with AJAX without the need for a <div> tag within the form

Utilizing an ajax call to dynamically update a select menu is a common practice. The ajax call fetches the options from a separate .php file and populates the select menu accordingly. Below is the code snippet for inserting the dynamic content using JavaS ...

Different sized image grid display

Could you please take a look at this screenshot: I am facing an issue with the grid layout. The first image in the grid is too short, which results in a big gap between the upper left and lower left pictures. Here is what it looks like currently: Is ther ...

Using a semicolon in the fall through of a switch case statement

When working with a fall-through in a case statement, is there any significance to including a semicolon? It seems that the fall-through functions as expected, and the semicolon may just be interpreted as an empty statement. But are there any advantages or ...

When running the command `npm run prod`, production mode is not activated in Vue.js

Currently, I am working on a project that involves Laravel and Vuejs. As part of the process, I tried to publish my website, but I keep encountering this particular message in the browser console. The message states that Vue is currently running in deve ...