How can CSS and JavaScript be used to strategically position two upright images next to each other within a dynamically resizing container?

Looking for a way to display two portrait images side by side within a flexible container with 100% width? The challenge I'm facing is accommodating varying widths of the images while ensuring they are the same height.

<div class="container">
       <p>Some Text</p>
       <img src="this-is-a-landscape-image.jpg" alt="test"/>
       <p> Some Text again</p>
       <img class="portait" src="this-is-a-portrait-image.jpg" alt="test"/>
       <img class="portrait" src="this-is-a-portrait-image.jpg" alt="test"/>
</div>

The issue at hand: I need to fit two images with the .portrait class into a responsive layout where the container's width is set at 100%. While the heights should be the same, the widths can vary due to different ratios of the images.

Is there a CSS solution using flexbox or perhaps a bit of JS that can achieve this without hardcoding the values as the content is generated dynamically through a CMS?

Do you have any innovative ideas to tackle this challenge?

Answer №1

It seems challenging to find a completely dynamic solution using only CSS, but I welcome any evidence to the contrary!

If you want to experiment with image sizes, window dimensions, and gutter width while maintaining consistent height for both images and proportional width, you can check out my quick jQuery solution here: http://jsfiddle.net/d2gSK/2/

The JavaScript code is as follows:

    // Encapsulate in a function for easy reuse
    function fitImages(img1, img2, gutter) {
        var $img1 = $(img1);
        var $img2 = $(img2);
        
        var ratio1 = $img1.width() / $img1.height();
        var ratio2 = $img2.width() / $img2.height();
        
        var targetWidth = $img1.parent().width() - gutter;

        var width1 = targetWidth / (ratio1+ratio2) * ratio1;
        var width2 = targetWidth / (ratio1+ratio2) * ratio2;

        $img1.width(width1);
        $img1.height(width1 / ratio1);
        $img2.width(width2);
        $img2.height(width2 / ratio2);

        $img1.css('paddingRight', gutter + 'px');

    }

    $(document).ready(function() {
        var $wrapper = $('.portrait-wrapper');
        fitImages($wrapper.children().get(0), $wrapper.children().get(1), 20);

        $(window).resize(function() {
            fitImages($wrapper.children().get(0), $wrapper.children().get(1), 20);
        });
    });

I have provided detailed explanations within the code itself. Feel free to ask if you need further clarification.

Keep in mind that I placed a wrapper around the images and applied display: block and float:left to them, as these styles are necessary for the functionality to work correctly!

Answer №2

One possible solution is outlined below:

<div class="wrapper">
    <p>Lorem Ipsum</p>
    <img src="landscape.jpg" alt="test"/>
    <p> More Lorem Ipsum</p>
    <div class="portraits">
        <img style="float:left;" class="portrait" src="portrait1.jpg" alt="test"/>
        <img style="float:right;" class="portrait" src="portrait2.jpg" alt="test"/>
    </div>
</div>

Answer №3

To break them out of the "normal flow", consider adding Float or even using position absolute, especially if the text between the top image and them remains consistent.

As for width, you can set their widths in percentage using pseudo classes - for example, give the first one 80% and the second 20%.

Another option is to create different CSS styles with specific page width breakpoints, like this:

@media screen and (max-width: 400px) {
   .portrait:first {
       width: 85px;
   }

   .portrait:last {
       width: 105px;
   }
}  

Repeat this process for each window size step as needed.

I hope this explanation helps!

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 the location where Three.js establishes the default shaders for materials?

I've been attempting to locate the exact location where the fragment and vertex shaders are being assigned after creating a Three.js material, but haven't had much success. Using the ParticleSystemMaterial, I have material = new THREE.ParticleSy ...

Having trouble grasping the problem with the connection

While I have worked with this type of binding (using knockout.js) in the past without any issues, a new problem has come up today. Specifically: I have a complex view model that consists of "parts" based on a certain process parameter. Although the entire ...

What rules should be followed in Python when it comes to using nested parentheses in functions?

Currently in the process of deleting my account from this platform, I am intentionally adding unnecessary content to this post. Please refrain from restoring the previous content. - Original Poster ...

What are the steps to perform typecasting in nodejs?

Struggling with converting string values to numbers and encountering an error. const express=require('express'); const bodyParser=require('body-parser'); const app=express(); app.use(bodyParser.urlencoded({extended:true})); app.get(&qu ...

Spin a sphere by clicking on a link using three.js

I've designed a spherical object and have a group of links. I'm looking for a way to manipulate the position or rotation of the sphere by simply clicking on one of the links. Despite extensive searching, I haven't been able to find an exampl ...

Tips on creating a unique d3js tree design

I am a beginner when it comes to d3js and javascript in general. My goal is to create an interactive IP administration overview using d3js by modeling json data. I know that the key tool for this job is likely d3.layout.tree, which will provide me with the ...

How to display a variety of JSON data in different templates with unique variables using angularjs

I am curious about the best approach to handling a response that contains various types of objects presented like this: [ {"nodeClass":"Entity", "text":"foo","entityfield":"booz"}, {"nodeClass":"User","username":"bar","userfield":"baz"} ] Each type of ob ...

Is it possible to replace the catch function in JavaScript with a custom function?

Below is the code snippet: function xyz() { try { var a = someexecutions(); handlesuccess(a) } catch (err) { handleerror(err) } } This type of function is repeated numerous times in my codebase and I am looking for a way to improve it. f ...

How can we display the Recent Updates from our LinkedIn profile on our website using iframe or javascript?

Currently, I am in the process of developing a .NET web application for our company's website. We already maintain an active LinkedIn profile where we regularly post updates. https://i.stack.imgur.com/T2ziX.png My main query at this point is whether ...

What is the best method for inserting the HTML content from a specific div into a textarea?

Everything seems to be working fine, but once I insert the HTML into the textarea, an issue arises where the div gets wrapped within another div, causing the layout to break. var urls = []; $('body').on('click', '.btn_video&apos ...

What could be the reason for the malfunction of my for loop within my JSON operation?

Hi everyone, I'm new to coding and currently working on a project involving Twitch Viewer on FreeCodeCamp. I've managed to extract information from the JSON file and display it in my HTML code. However, I'm encountering an issue where I am ...

Is it possible to delay the loading of a page using location.href?

Trying to determine when a page has finished loading using location.href. Currently, my code is set up like this and I want certain events to occur once the page is fully loaded. I attempted using $.get but encountered issues with my existing implementatio ...

Using the prop callback in a React test renderer does not trigger updates in hooks

I am currently exploring ways to effectively test a React function component that utilizes hooks for state management. The issue I am encountering revolves around the onChange prop function not properly updating the state value of my useState hook. This in ...

The IE condition is failing to work properly with .js and .css files

I've been trying to use this code to load the ie.css file specifically for IE browsers, but for some reason it's not working. I'm feeling a bit confused here - can anyone help me figure this out? <html> <head> <titl ...

Tips on resolving the distinct key issue in React and eliminating it

Attention all React beginners! I'm encountering an issue that states: Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `resultTable`. See https://fb.me/react-warning-keys for more information. ...

Tips on personalizing the default html template in nuxt

Struggling to customize the default page from my Nuxt app due to limited documentation. Link to Documentation I'm interested in extracting only certain elements like the title or links in the head section. For example, how can I access just the li ...

Multiple columns contained within a span

I'm trying to create a panel that displays a list of values with corresponding labels. The requirement is for each label to be positioned above its respective value and aligned to the left. The layout should resemble the following: Label 1 Lab ...

Date Boxes in a Tangled Web

Looking to showcase multiple dates on a screen, I'm encountering an issue where clicking on a date button opens a datepicker. If the user clicks out of the box, the datepicker closes properly. However, when another datepicker button is clicked, instea ...

Enable the input field once the checkbox has been marked

Here is a checkbox example: <div class="form-group"> <input type="checkbox" id="examination" class="form-control" name="exam" placeholder="Enter Title"> <label>Enable Exam</label> </div> Additionally, I have a disabled inpu ...

Utilizing IndexedDB for data storage

Hey there! I am currently working on storing three fields in an IndexedDB. When I view them in the browser, I see the names of each index - content, content2, and content3. However, only data is being saved into content3. Can you help me figure out why? B ...