When images are placed within a div, they become tightly packed together and do not allow

I am looking to display the uploaded images in a div while maintaining their width, height, and spacing between them. They should also be horizontally scrollable if they overflow the div.

document.querySelector("#files").addEventListener("change", (e) => {
    if (window.File && window.FileReader && window.FileList && window.Blob) {
        const files = e.target.files;
        const output = document.querySelector("#result");
        const div = document.createElement("ul");
        for(let i = 0; i < files.length; i++){
            if (!files[i].type.match("image")) continue;
            const picReader = new FileReader();
            picReader.addEventListener("load", function(event) {
                const picFile = event.target;
                const div = document.createElement("div");
                div.innerHTML = `<img class="thumbnail" src="${picFile.result}" title="${picFile.name}"/>`;
                output.appendChild(div);
            })
            picReader.readAsDataURL(files[i]);
        }
    } else {
        alert("Your browser does not support File API")
    }
})
#result {
    display: flex;
    margin-top: -60px;
    margin-left: 70px;
    height: 65px;
    background-color: yellow;
    width: 80%;
    overflow-x:auto;
    overflow-y:hidden;
}

.thumbnail {
    height: 60px;
    width: 60px;
    border-radius: 6px;
}
<div id="result"> </div>

current output

Answer №1

#container {
    /* Adjust the height of the parent to automatically adjust the height of images and buttons */
    --height: 15vw;
    /* Default scrollbar height is 12px (at least in chrome), 
    added extra pixel for compatibility with Firefox etc... 
    can be manually adjusted here or...
    /* Scrollbar width can also be adjusted using javascript https://stackoverflow.com/questions/28360978/css-how-to-get-browser-scrollbar-width-for-hover-overflow-auto-nice-margi */
    /* CSS var used in line 35 (#result .thumbnail) */
    --scrollBarHeight: 15px;
    border: 1px solid red;
    /* button (auto width) #result (all space) */
    display: grid;
    grid-template-columns: auto 1fr;
    /* gap between buttons and #result, change if needed */
    gap: 1rem;
}

#container button {
    /* Square button */
    height: var(--height);
    width: var(--height);
    /* Font size auto adjusts based on button height */
    font-size: calc(var(--height) / 1.5)
}

#result {
    height: var(--height);
    /* Displayed side by side */
    display: flex;
    gap: 0.5rem;
    /* Activate scrollbar */
    overflow-x: scroll;
}

#result .thumbnail {
    /* Fixing "scrollbar covering images" issue */
    height: calc(var(--height) - var(--scrollBarHeight));
    /* Preserve image aspect ratio */
    object-fit: cover;
}
<!-- Example usage -->
<div id="container">
  <!-- Add button -->
  <button>+</button>

  <!-- Container for images -->
  <div id="result">
    <!-- 1 --><img class="thumbnail" src="https://picsum.photos/500" alt="">
    <!-- 2 --><img class="thumbnail" src="https://picsum.photos/500" alt="">
    <!-- 3 --><img class="thumbnail" src="https://picsum.photos/500" alt="">
    <!-- 4 --><img class="thumbnail" src="https://picsum.photos/500" alt="">
    <!-- 5 --><img class="thumbnail" src="https://picsum.photos/500" alt="">
    <!-- 6 --><img class="thumbnail" src="https://picsum.photos/500" alt="">
    <!-- 7 --><img class="thumbnail" src="https://picsum.photos/500" alt="">
    <!-- 8 --><img class="thumbnail" src="https://picsum.photos/500" alt="">
    <!-- 9 --><img class="thumbnail" src="https://picsum.photos/500" alt="">
    <!-- 10 --><img class="thumbnail" src="https://picsum.photos/500" alt="">
  </div>
</div>

Answer №2

To solve this issue, simply include a gap property within the #result div and apply flex-shrink:0; to the parent div of the .thumbnail image element.

The rationale behind this adjustment is that flexbox inherently tries to shrink all its child elements to fit them on a single line. Regardless of their size, it will reduce them to ensure they align in a row.

const picFile = event.target;
const div = document.createElement("div");

div.className="thumbnail-container"
div.innerHTML = `<img class="thumbnail" src="${picFile.result}" title="${picFile.name}"/>`;
output.appendChild(div);
#result {
    display: flex;
    margin-top: -60px;
    margin-left: 70px;
    height: 65px;
    background-color: yellow;
    width: 80%;
    gap:20px;
    overflow-x:auto;
    overflow-y:hidden;
}

.thumbnail {
    height: 60px;
    width: 60px;
    border-radius: 6px;
}
.thumbnail-container{
   flex-shrink:0;
}

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 on eliminating expansion upon button click in header within an Angular application

While utilizing Angular Materials, I encountered a challenge with the mat-expansion component. Every time I click on the buttons within the expansion panel, it closes due to the default behavior of mat-panel. Requirement - The panel should remain expanded ...

The issue arises when attempting to apply styling to a table row using the tr:hover CSS selector in IE 8, specifically when hovering over an input text field nested within div and td elements

When hovering over the row (tr), the tr:hover rule is being applied. However, when hovering over the child text content of the tr input, the tr:hover rule is not being applied. This issue is specific to IE-8. Can anyone help me identify the root cause? N ...

The second tab on Bootstrap5's tab content feature seems to generate an endless amount of white

I am working on a project where I need to display statistics for both the current month and year. To organize this data, I created a card with tabs for each - one tab for the month and another for the year. By default, the month tab is loaded first. Howev ...

Stop storing CSS data for nopCommerce

Currently, I am looking for a method to avoid caching CSS files on my nopCommerce website. In the past, I have achieved this by adding the date and another element at the end of the CSS call. Html.AppendCssFileParts("~/Themes/CustomTheme/Content/css/site. ...

Straightening the border of the final item

In my Angular project, I'm currently implementing a progress bar with the following code: .bar { --d: 1rem; /* arrow depth */ --gap: 0.3rem; /* arrow thickness, gap */ display: flex; margin-right: var(--d); } .bar-step { flex: 1; ...

Utilizing AngularJS ng-repeat with a two-dimensional array

Would it be possible to incorporate ng-repeat within a div like the following? <li ng-repeat="image in HomeCtrl.images.data" > <a ng-href="@{{ image.code }}"><img ng-src="@{{ image.url }}" ></a> </li> Displayed below is ...

Separate a string into individual parts while also including the separators as their own values within

Looking for help with extracting numbers and operators from basic math equations. Is there a way to split each number into an array while keeping the operator separate? "123/12*312+4-2" The desired output is as follows: ["123", "/", "12", "*", "312", "+ ...

Managing nested levels in Vue Draggable

Here is a link to the code sandbox: Nested Draggable Code Sandbox The nesting in this code is controlled through directives, specifically using v-if: <template> <draggable class="dragArea" tag="ul" :list="tasks" :g ...

What is the best way to transform a 2D array into a grid of card components using React JS and Material-UI components?

I have been presented with a 2D array of objects and my task is to transform it into a matrix of cards, where each card will display text retrieved from the object. I have utilized the .map function but faced undesired results when working with the followi ...

Retrieving the selected value from a Bootstrap dropdown using JavaScript when there are multiple dropdowns present

I have created multiple rows in javascript that are being rendered to the DOM from a Firestore collection. Each row contains a Bootstrap dropdown with the same select options (".a" elements). The id attribute of each row div is dynamically set based on the ...

Leveraging an array of Elasticsearch documents using AngularJS

The query results are given below... { "took": 6, "timed_out": false, "_shards": { "total": 5, "successful": 5, "failed": 0 }, "hits": { "total": 45, "max_score": 0, "hits": [] }, "aggregations": { ...

HTML5 Canvas - Creating several drawing instances

Running multiple drawings in canvas can lead to issues if timing is not properly managed. For example, drawing a line with a certain interval and then duplicating the line while setting each one's stroke color differently may result in colors bleedin ...

Go through each .md document, transform them into HTML format, and dispatch them

I am using fs to read files in .md format and transform them into HTML files. Here is the code snippet I have written: fs = require('fs'); fs.readFile(__dirname + '/posts/react-v16.13.0.md', 'utf8', function (err, data) { i ...

Is there a way to replace the message 'no rows to show' with a custom component in ag-Grid for react?

Currently, I am utilizing ag-grid in my React application https://www.ag-grid.com. When the table or grid is empty, it displays the default message "No rows to show." However, I am interested in customizing this message or possibly incorporating a custom ...

Why is the model so tiny after converting my FBX file to a .gltf format?

QUERY: I am facing an issue where my model appears extremely small after converting the FBX file to a .gltf format. Despite attempting to scale the model using frontObject.scale.set(1000, 1000, 1000);, I encounter the following error: TypeError: Cannot r ...

The sorting functionality in Angular.js using the orderBy directive seems to be malfunctioning as it is not

Within this code snippet, @Model.jsonString represents a string. @model WebApplication1.Models.Car @{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } <html> ... <body ng-app="myModule"> <div ng-controller="myC ...

Conceal the Addon Tab across all pages in Storybook

Is there a way to globally hide an Addon Tab without disabling the addon itself? Specifically, I am using version 5.3.18 of Storybook with React and I want to hide the tab panel from the addon "styled-component theme". I apologize for the basic question, ...

npm does not accommodate the current version of Node.js (vX.X.X)

Today, I am attempting to install the most recent version of Node.js (13.12.0) along with npm. However, I have encountered an issue because the latest npm version (6.14.4) does not support this Node.js version, resulting in the following error message: np ...

Tips for moving a div with a button in jQuery

I am working on a parent div that has an overflow set to hidden and it contains dynamically created children. I want to be able to scroll the parent div using two buttons - one for scrolling up and the other for scrolling down, as if the div had overflow-y ...

Share the hyperlink to a webpage with someone else

In my SQL command, I have a unique feature that retrieves the complete URL value of the current page: [##cms.request.rawurl##]. This code returns the entire URL. I need to send this address to another page and load it into a special div called "load-fac". ...