Choose an image to be displayed at either full width or full height, depending on which dimension is reached first

I have a query regarding resizing an image within a div to either 100% width or 100% height of the containing div. Despite setting max-height and max-width to 100% as recommended here, I still encounter overflow issues without wanting to crop the image using overflow:hidden. The image is floated within the div.

Is there a way to achieve this? Here is my code. Could there be something wrong with it?

div#_content div#_thumbnails div {
  padding:2px;
  display:inline-block;
  min-width:10%;
  max-width:25%;
  min-height:80px;
  max-height:125px;
  text-align:center;
}
div#_content div#_thumbnails img {
  display:inline;
  padding:2px;
  float:left;
  max-height:100%;
  max-width:100%;
}

In the following JavaScript snippet, imgs represents a list of URLs and thumbnails is the main div for the containers to be placed in.

for (i in imgs) {
  if (imgs[i]) {
    var new_img = document.createElement('IMG'),
      container = document.createElement('DIV')
    new_img.setAttribute('alt', "image"+i.toString())
    new_img.setAttribute('src', imgs[i])
    container.appendChild(new_img)
    thumbnails.appendChild(container)
  }
}

I apologize if this question seems trivial, but despite my efforts in searching for solutions, none seem to work.

Answer №1

Here is a suggestion for your code:

<style type="text/css>
#thumbContainer {
    position:relative;
}
.thumb{
    position:relative;
    float:left;
    width: 100%;
    height: auto;
}
.thumb img {
    background-size: cover !important;
    width: 100%;
    height: auto;
}
</style>

<div id="thumbContainer">
    <div class="thumb"><img src="http://3.bp.blogspot.com/_ABFjy8u6h9s/TStw8-_4j1I/AAAAAAAACE0/cKm4ZiIFilk/s1600/NATUREZA+01.jpg" /></div>
    <div class="thumb"><img src="http://3.bp.blogspot.com/_ABFjy8u6h9s/TStw8-_4j1I/AAAAAAAACE0/cKm4ZiIFilk/s1600/NATUREZA+01.jpg" /></div>
    <div class="thumb"><img src="http://3.bp.blogspot.com/_ABFjy8u6h9s/TStw8-_4j1I/AAAAAAAACE0/cKm4ZiIFilk/s1600/NATUREZA+01.jpg" /></div>
</div>

(http://jsfiddle.net/ahjjg/)

Furthermore, consider using a background instead of an <img> tag.

Answer №2

For those utilizing PHP, look no further as this solution is tailored just for you.

Discover the ultimate fix for image resizing based on width and height here

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

Node development does not operate continuously

I'm facing a minor issue with node-dev. I followed the instructions in the readme file and successfully installed it. However, when I run the command like so: node-dev somescript.js, it only runs once as if I used regular node without -dev. It doesn&a ...

Extract the year from a string formatted as 1880-01-01T00:00:00.000

Looking to extract the year from an array of dates with format 1880-01-01T00:00:00.000. What's the most efficient method to accomplish this using JavaScript? ...

Strategies for managing grid overflow situations

Check out my codepen showcasing the current issue I'm dealing with: https://codepen.io/marcdaframe/pen/qeBWNd <div> 123 abc <div class="container"> <div class="wrapper"> <div>One</div> <div>Two</div> ...

Issue with react-addons-css-transition-group and multiline TextFields in Material-UI TextField

If a TextField with multiline is nested inside a react-addons-css-transition-group, it seems to disrupt the show transition. Any suggestions on how to handle this situation effectively? Check out my code snippet here: https://codesandbox.io/s/material-dem ...

Is there a way to resolve this issue? (An error occurred: TypeError - res.json is not a valid function)

When attempting to add an object to my MongoDB database const response = await fetch("/api/contact", { method: "POST", body: JSON.stringify(data), headers: { "Content-Type": "application/json", }, }); I encounter the error message ...

Tips for populating a textfield with data from a <select> dropdown using javascript

Is there a way to populate a textfield with data automatically based on information provided in the tab, utilizing JavaScript? Additionally, is it possible to prevent the filled data from being edited? The textfield should be able to dynamically fill data ...

Guide to retrieving the previous URL in Angular 2 using Observables

Can someone help me retrieve my previous URL? Below is the code snippet I am working with: prev2() { Promise.resolve(this.router.events.filter(event => event instanceof NavigationEnd)). then(function(v){ console.log('Previous ' ...

Trouble with Click event not working in Electron and mouse cursor not changing when hovering over an HTML button?

I'm in the midst of a project that involves using the electron framework. Within my project, I have an HTML file, a CSS file, and a Javascript file. The issue at hand is that when I hover over a button, the expected hand pointer icon fails to appear d ...

Ways to retrieve an array saved in another JavaScript document

I am in the process of developing my own lorem ipsum application and keen on maintaining clean code by storing my word bank in separate files. How can I retrieve an array stored in a different JavaScript file? Rather than manually inputting harry = ["", "" ...

Managing images in JavaScript while conserving memory

Welcome I am embarking on a project to construct a webpage using HTML, CSS, JavaScript (jQuery), and nearly 1000 images. The length of the HTML page is substantial, around 5000px. My vision involves creating a captivating visual experience for users as t ...

showing images received via a websocket connection

My current setup involves receiving one image per second through a WebSocket connection. The images are in blob format, and I am unsure of the best way to display them. Should I use an image tag or a video player? And how should I go about showing these ...

Looking for a condensed version of my app script to optimize speed and efficiency

In my script, users input data and run the script by clicking a button. The script then appends the data to two different tabs and clears the data entry tab. However, I encountered an issue where I had to manually hard code each cell for appending, causi ...

Triggering an Ajax request by clicking on a link

In the scenario where you have a specific word on a webpage that you would like to trigger an onclick event and initiate an ajax request, what is the best approach to accomplish this? ...

Is there a way to include a minimize button on a MaterialUi Table enclosed in a Paper component for easy table reduction?

I am trying to add a minimize button to either minimize my MaterialUi Table or the Paper component that wraps it. Here is the code I have so far: <TableContainer component={Paper} style={{maxHeight:'inherit', maxWidth:'inherit', boxS ...

Delete the content on a webpage using an Ajax jQuery request to transfer it elsewhere

Whenever I submit a form using an ajax post request, I receive values from the controller and manipulate the page based on those values. However, my issue is that I need to erase the values from the previous request when the form is submitted again. For in ...

When refreshed using AJAX, all dataTable pages merge into a single unified page

I followed the instructions on this page: How to update an HTML table content without refreshing the page? After implementing it, I encountered an issue where the Client-Side dataTable gets destroyed upon refreshing. When I say destroyed, all the data ...

What is the recommended lifecycle hook in Vue.js2 to execute a function when the page is loaded?

I have a dynamic table that can be filled with various numbers of rows, and I want to add an overlay before the data is loaded using my applyOverlay() function. Below is the structure of my HTML: <table id="table" class="datatable" s ...

Exploring Node troubleshooting with WebPack and Feathers

Currently, I am part of a team working on a project that involves using Node, Webpack, TypeScript, and Express/Feathers. While my fellow developers are experienced in these technologies, I have limited experience with JavaScript mainly on the client-side a ...

Finding the source of the err.kind expression in the MERN stack: Unraveling the mystery

Recently, I've been delving into the world of MERN stack development and came across an interesting technique for Error Handling in a tutorial. The tutorial showcased various expressions that can be used to identify different types of errors being thr ...

I'm looking for a way to track the progress of an ajax call. Specifically, I want to know how I

I am currently working on an AJAX call that executes a lengthy PHP script producing 20 different results. I aim to display the progress of each step within the script, such as 1/20 complete, 2/20 complete, 3/20 complete. Last updated on 29-12-2015 at 03:1 ...