Containers for Comparing Images are Unable to Flexibly Wrap

Check out my codepen project here: https://codepen.io/Bryandbronstein/pen/NLVQjB

I've encountered a peculiar issue while experimenting with CSS and Javascript. I came across an image comparison slider on the W3C website that worked flawlessly as a single element. However, when I tried to create a gallery of these sliders, they refused to adhere to the flex rules I set for their parent container. As you can see in the codepen, one comparison container is hidden behind another. Any solutions or suggestions?

I have been exploring some advanced techniques... 
I have defined some custom styles in my CSS...
 <body onload="initComparisons();">

<div class="row">
  <div class="img-comp-container" >
    <div class="img-comp-img">
      <img src="..." width="500" height="450">
    </div>
    <div class="seperator"></div>
    <div class="img-comp-img img-comp-overlay">
      <img src="..." width="500" height="450">
    </div>
  </div>
  
  (Repeat the above block for additional images)

</div>

</body>

Answer №1

The issue with the images not wrapping was due to all children of .img-comp-container being absolutely positioned. This caused the flex elements to collapse, preventing the flex wrap from functioning properly.

To resolve this, you can either make one or more children of .img-comp-container relative or static, or set a specific width and height for .img-comp-container.

Below are the CSS changes I implemented:

.img-comp-container{
  position: relative;
  flex: 50%;
}

.img-comp-img {
  position: relative;
  width: auto;
  height: auto;
  overflow: hidden;
}

.img-comp-overlay {
  border-right: 2px solid rgba(51, 51, 51, 0.5);
  position: absolute;
  top: 0;
  left: 0;
}

You can view a working solution by checking out this codepen fork based on your pen.

Answer №2

function initializeComparisons() {
          var y, j;
          /*find all items with an "overlay" class:*/
          y = document.getElementsByClassName("img-comp-overlay");
          for (j = 0; j < y.length; j++) {
            /*for each "overlay" item:
            pass the "overlay" item as an argument when running the compareImages function:*/
            compareImages(y[j]);
          }
          function compareImages(img) {
            var slider, image, clicked = 0, width, height;
            /*obtain the width and height of the img element*/
            width = img.offsetWidth;
            height = img.offsetHeight;
            /*set the width of the img element to 50%:*/
            img.style.width = (width / 2) + "px";
            /*create a slider:*/
            slider = document.createElement("DIV");
            slider.setAttribute("class", "img-comp-slider");
            /*insert slider*/
            img.parentElement.insertBefore(slider, img);
            /*position the slider in the middle:*/
            slider.style.top = (height / 2) - (slider.offsetHeight / 2) + "px";
            slider.style.left = (width / 2) - (slider.offsetWidth / 2) + "px";
            /*run a function when the mouse button is pressed:*/
            slider.addEventListener("mousedown", slideReady);
            /*and another function when the mouse button is released:*/
            window.addEventListener("mouseup", slideFinish);
            /*or touched (for touch screens:*/
            slider.addEventListener("touchstart", slideReady);
             /*and released (for touch screens:*/
            window.addEventListener("touchstop", slideFinish);
            function slideReady(e) {
              /*prevent any other actions that may occur when moving over the image:*/
              e.preventDefault();
              /*the slider is now clicked and ready to move:*/
              clicked = 1;
              slider.style.border = "0";
              /*run a function when the slider is moved:*/
              window.addEventListener("mousemove", slideMove);
              window.addEventListener("touchmove", slideMove);
            }
            function slideFinish() {
              /*the slider is no longer clicked:*/
              clicked = 0;
              slider.style.border = "3px solid white";
            }
            function slideMove(e) {
              var position;
              /*if the slider is no longer clicked, exit this function:*/
              if (clicked == 0) return false;
              /*get the cursor's x position:*/
              position = getCursorPos(e)
              /*prevent the slider from being positioned outside the image:*/
              if (position < 0) position = 0;
              if (position > width) position = width;
              /*run a function that will resize the overlay image according to the cursor:*/
              slide(position);
            }
            function getCursorPos(e) {
              var b, x = 0;
              e = e || window.event;
              /*get the x positions of the image:*/
              b = img.getBoundingClientRect();
              /*calculate the cursor's x coordinate, relative to the image:*/
              x = e.pageX - b.left;
              /*consider any page scrolling:*/
              x = x - window.pageXOffset;
              return x;
            }
            function slide(x) {
              /*resize the image:*/
              img.style.width = x + "px";
              /*position the slider:*/
              slider.style.left = img.offsetWidth - (slider.offsetWidth / 2) + "px";
            }
          }
        } 
html, body { 
          background-color: #333333;
          margin: 0;
          padding: 0;
         }

        * {box-sizing: border-box;}

        .gallery_text {
          color: white;
          font-family: Abel, Helvetica, sans-serif;
          font-size: 1.7rem;
          text-align: center;
          line-height: 1.8em;
        }

        .row{
          display: flex;
          flex-wrap: wrap;
          justify-content: center;
          align-items: center;
        }

        .img-comp-container{
          position: relative;
          flex: 50%;
        }

        .img-comp-overlay{
          border-right: 2px solid rgba(51,51,51, .5) ;
        }

        .img-comp-img {
          position: absolute;
          width: auto;
          height: auto;
          overflow: hidden;
        }

        .img-comp-img img {
          vertical-align: middle;
        }

        .img-comp-slider {
          position: absolute;
          z-index: 9;
          cursor: ew-resize;
          width: 40px;
          height: 40px;
          transform: rotate(136deg);
          background-color: #333333;
          opacity: .8;
          border-radius: 10%;
          border: 3px solid white;
        }
 <body onload="initializeComparisons();">

    <div class="row">

            <div class="img-comp-container" >
              <div class="img-comp-img">
                <img src="https://images.pexels.com/photos/162389/lost-places-old-decay-ruin-162389.jpeg?cs=srgb&dl=black-and-white-dark-building-162389.jpg&fm=jpg" width="500" height="450">
              </div>
                <div class="separator"></div>
              <div class="img-comp-img img-comp-overlay">
                <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSslfAcWKXuMxBpzcJC5ZUyFqMOb2Jtd12x4kBUGG9mTe3KeMJz" width="500" height="450">
              </div>
            </div>

            <div class="img-comp-container">
              <div class="img-comp-img">
                <img src="https://images.pexels.com/photos/162389/lost-places-old-decay-ruin-162389.jpeg?cs=srgb&dl=black-and-white-dark-building-162389.jpg&fm=jpg" width="500" height="450">
              </div>
                <div class="separator"></div>
              <div class="img-comp-img img-comp-overlay">
                <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSslfAcWKXuMxBpzcJC5ZUyFqMOb2Jtd12x4kBUGG9mTe3KeMJz" width="500" height="450">
              </div>
            </div>

            <div class="img-comp-container">
              <div class="img-comp-img">
                <img src="https://images.pexels.com/photos/162389/lost-places-old-decay-ruin-162389.jpeg?cs=srgb&dl=black-and-white-dark-building-162389.jpg&fm=jpg" width="500" height="450">
              </div>
                <div class="separator"></div>
              <div class="img-comp-img img-comp-overlay">
                <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSslfAcWKXuMxBpzcJC5ZUyFqMOb2Jtd12x4kBUGG9mTe3KeMJz" width="500" height="450">
              </div>
            </div>
        
    </div>

</body>

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

Page not found: unique error on alternate route

My website has different paths and pages in hbs format, such as root, help, and 404. The problem arises when I navigate to localhost:3000/wrong, the site displays correctly, but when I try localhost:3000/help/wrong, the CSS is not applied to the 404 page b ...

Steps to initiate my selenium-standalone server: Execute the command "selenium-standalone start"

I'm currently facing a challenge while trying to execute a test script in WebDriverIO. After cloning the code from wdio-cucumber-framework, I am unable to get selenium-standalone to start properly. The error message indicates an issue with geckodriv ...

Incorporating a stationary sidebar onto your website

My goal is to create a fixed side menu similar to the one on this website: Below is my HTML code: <!-- Scroll TEST --> <ul id="followTab"> <li> <a class="newsletter" href="newsletter/" title="Subscribe to ..."> ...

Scaling the ion-spinner to fit your specific needs

In my Ionic application, I am utilizing the ion-spinner. However, I have encountered an issue with resizing the spinner. While custom CSS works well with default spinners, it does not function properly with Bubbles, Circles, and Dots spinners. CSS .spin ...

I am creating an HTML page that incorporates p5.js, and the text I'm rendering

It seems like the draw loop is continuously refreshing every x seconds, causing this behavior. Is there a way to slow down or disable the frame update without affecting the video refresh rate? I was thinking of adding an fps counter and implementing an i ...

The error message "Angular - ReferenceError: angular is not defined" indicates that the Angular

When attempting to incorporate a simple Angular function into my Laravel 5 project, I encountered the following error: angular is not defined Even after moving angular.min.js to the top of my index page as the first JS script, the issue persists. You ...

Issue with enlarging images using UL and LI tags persists

After implementing the code for a simple image enlarge feature (showing a QR code image when the user hovers over the icon), I noticed an issue. Interestingly, the same code is used on two designs, but it's not working on one of them. To view the pr ...

What is the best way to include an icon with dropdown menu options?

I am facing an issue with a text box and modifier dropdown. I want to display an icon representing the current choice when selected. However, using UNICODE for icons causes them not to display properly in certain browsers like Google Chrome unless specific ...

Can you suggest an alternative for the "return" statement within a "for loop" in order to retrieve all values from the loop?

When using numInOrder + " : " + nameInOrder;, the console only displays one value: "1 : a". However, I would like to see: "1 : a 2 : b 3 : c 4 : d 5 : e 6 : f" in the console.log output. Additionally, I do not want to use consol.log(numInOrder + " ...

Interacting with browser logs using C# Selenium

Is it possible to extract browser logs in C# using selenium? I want to document any JavaScript errors that show up on a specific webpage, ideally on Chrome or Firefox. I've managed to do this before with Python, but I'm wondering if it's a ...

The background color in CSS frames the text with a unique hue

Is there a way to wrap my multi-line text inside a div with a background color that automatically adjusts its size based on the text length? .multiline{ padding:0px; white-space: pre-wrap; height: 100px; width: ; margein:0px } <div style="b ...

The auto-complete feature is malfunctioning after retrieving input suggestions from a PHP file

My goal is to achieve the following: 1. Create a list of suggestions with same labels but different descriptions. 2. Upon selecting an item from the list, the input field of another item should change to the corresponding description of the selected item. ...

What is the antonym of a 'click' event when using .addEventListener?

I'm curious if there is a complementary event to 'click' that can be used with .addEventListener. My goal is to have a click event empty the search bar when activated, and then return the default text 'Search..' when the user click ...

Creating a TypeScript object declaration

I am looking for some help with converting this JavaScript code to TypeScript. I am new to both languages, and when trying to access the 'this' object in my TypeScript version, I get an error message saying that 'this possibly be unknown&apo ...

Sharing variables between Angular 2 components: An in-depth guide

Looking for a way to change a variable in a group of child components, I have this component for an editable form control that toggles between view states import { Component, Input, ElementRef, ViewChild, Renderer, forwardRef, ...

I recently started a project using create-react-app on my Windows computer. However, I encountered an error when I attempted to run npm start in the command line. Can anyone assist me in resolving this issue

Encountered an npm start error Error: code ELIFECYCLE npm ERR! errno 1 npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the [email protected] start script. npm ERR! No problem with npm. Look for additional logging. npm ERR! Check log here: npm ERR! ...

RxJS: Transforming an Observable array prior to subscribing

I am retrieving data (students through getStudents()) from an API that returns an Observable. Within this result, I need to obtain data from two different tables and merge the information. Below are my simplified interfaces: export interface student Stude ...

The Vue 2.0 instance seems to be failing to listen to events emitted by vue-router components

Currently, I am working with Vue 2.0-rc.6 and Vue-router 2.0-rc.5, the latest versions available. I attempted to use this.$emit('custom-event') in one of my router components and this.$on('custom-event', () => { console.log('I ...

What is the advantage of utilizing AngularJs .constant() over simply declaring a JavaScript const variable?

Currently, I am involved in a project using AngularJS where we have implemented a .constant() provider to define some fundamental details that are utilized throughout the entire project. An example of this would be specifying a cookie name like so: .const ...

Retrieving the background image URL from inline CSS using jQuery

I'm looking for a link similar to url(img/bg/06.jpg), but when using jQuery, I get a longer link like url("file:///D:/WORKING%20FILE/One%20Landing%20Page/version/img/bg/06.jpg") https://i.stack.imgur.com/8WKgv.png Below is the code snippet in questi ...