Ensure that a child container automatically adjusts its width to fit within a parent container of varying width

There is a wrapping container that contains three floated containers inside. The width of the wrapping container is variable. The inner container on the left has a width of 100px, and the inner container on the right has a width of 500px. The center container does not have a fixed width and should take up the remaining space.

<style type="text/css">
    #outerContainer div:nth-child(1) {float: left; width: 100px}
    #outerContainer div:nth-child(2) {float: left}
    #outerContainer div:nth-child(3) {float: right; width: 500px}
</style>

<div id="outerContainer">
    <div>left most inner container</div>
    <div>center container</div>
    <div>right most inner container</div>
</div>

The center container has some styles applied to it to hide overflow and add ellipsis for better presentation.

<style type="text/css">
#outerContainer div:nth-child(1) {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
</style>

Looking for a CSS-only solution to dynamically adjust the width of the center container. Below is a JavaScript solution that's currently being used, but it seems too complex.

NS.textWidth = function(sourceSel){
    var sourceSel = sourceSel,
        html_org = $(sourceSel).html(),
        html_calc = '<span>' + html_org + '</span>';

    //Wrap contents with a span.
    $(sourceSel).html(html_calc).css({width:'100%'});
    //Find width of contents within span.
    var width = $(sourceSel).find('span:first').width();

    //Replace with original contents.
    $(sourceSel).html(html_org);

    return width;
};

adjustContainerWidth();

$(window).bind('resize', function(e){
    clearTimeout(c.resize_timeout);

    c.resize_timeout = setTimeout(function() {
        adjustContainerWidth();
    }, 200);
});

function adjustContainerWidth() {
    var winW = parseInt($(window).width());
    var firstContainer = parseInt($('#outerContainer div:nth-child(1)').width());
    var lastContainer = parseInt($('#outerContainer div:nth-child(3)').width());
    var availW = winW - firstContainer - lastContainer;
    var textW = NS.textWidth('#outerContainer div:nth-child(2)');

    if (availW > 40 && availW < textW) {
        $('#outerContainer div:nth-child(1)').css({ width : availW + 'px' });
    } else {
        $('#outerContainer div:nth-child(1)').css({ width : textW + 'px' });
    }
}

Answer №2

This code snippet is untested but should do the job. It calculates the width of the parent element, the combined width of its sibling elements, and then sets the width of the current element accordingly:

var that = $(this),
    parentWidth = that.parent().width(),
    siblingsWidth = 0;

that.siblings().each(
    function(){
        siblingsWidth += $(this).outerWidth();
    });

that.width(parentWidth - siblingsWidth);

Check out the JS Fiddle demo to see it in action.

In the demo, the #outerContainer element is set to 1000px wide to ensure all elements have enough space. Also, a correction was made to the CSS to match elements correctly; CSS is one-based, not zero-based like programming languages.

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

Creating dependent dropdown lists is a useful way to streamline data entry and ensure accuracy in your

I am looking to create a series of 4 connected dropdown lists, structured like this: District: <select id="district"> <option>Select a District</option> <option value="district1">dstrict1</optio ...

The contents of the image are currently unable to be viewed

I have a Blob of an image that I am trying to display in the browser. However, when I use the code below to open the image, it shows some Mandarin scripts on the window. Here is the code snippet: var url="http://....link..../downloadFile?fdsFileId="+file ...

How come the nth-child selector remains unaffected by other selectors?

Here is an example that I have created for this issue: http://jsfiddle.net/SXEty/ <style> table td, th { padding: 8px; text-align: left; } table td:nth-child(1) { color: red; } table td { color: blue } </style> ... <table> <tr> ...

Each loop iteration results in the array being randomly ordered

My goal is to store multiple objects in an array and then render them out in a specific order. This is my process: app.js var allOdds = []; var count = 0; // ===================================== /* Database Configuration and Error Handling */ // ====== ...

Adding numbers to a textbox using a JavaScript algorithm

There are two textboxes in this scenario. The first box should always contain 4 digits when you leave it, while the second box should always contain 10 digits. A javascript function needs to be implemented so that when a user leaves one of the textboxes, ...

When working with ReactJS and NextJS applications, the variables declared in the .env file may sometimes be received as undefined

In my .env.local file, the following variable is defined: REACT_APP_API_PATH=http://localhost:3600/ The .env.local file can be found at the root level of the project directory. Here is how I am attempting to utilize this variable: console.log('node ...

Obtain the data of the highlighted row in a telerik grid directly from the client side

I am attempting to retrieve the value of a GridBoundColumn with DataField="id" using JavaScript on the client side. When the user clicks on the image button within a row, I need to extract the id for that specific row and then invoke a web method by passin ...

Converting string patterns to regular expressions

I am utilizing mongodb to store data. My requirement is to save complete regular expressions as strings: { permissions: [{ resName: '/user[1-5]/ig', isRegex: true }] } Although I am aware of the existence of the module mongoose-rege ...

Change all instances of the subtraction symbol to parentheses using jQuery

--html-- <table> <tr> <th>a</th> <th>b<th> </tr> <tbody class = "tabledata"> <tr>a</tr> <tr>b</tr> </tbody> </table> --jquery-- $('.tabledata').empty(); for ( ...

Gallery Pagination using JQuery is not working properly

I am experimenting with the jquery easy paginate plugin on a separate page of my Blogspot. The images are displaying properly, but the pagination and CSS are not showing up. I need to adjust my CSS to make this jQuery pagination work correctly. Can someone ...

Adjust the transparency of a separate image within a different container by hovering over another image container

Is my goal too complex to achieve? I am attempting to create a hover effect where the opacity of artwork1 and button1 changes simultaneously when hovered over. However, I am having trouble properly labeling my elements and getting them to interact as inten ...

Setting a background image as a variable in Vue.js

I am currently working on a vue.js component that includes a div.icon: Vue.component('obj', { props: ['img', 'name'], template: '<div><div class="icon"></div> {{ name }}</div>' }) While ...

Utilizing an Empty Array within an AngularJS Controller Function Invoked by a Directive

I have encountered a tricky issue that appears to be simple, but I am struggling to find a solution. Currently, I am developing a to-do list application using Angular and Angular-Material. The main part of the application is located in a file named main. ...

Tracking dynamic collections in AngularJS ng-repeat using track by

I am attempting to utilize ng-repeat with the result of a function call, like this: <body ng-init='a = [1, 2, 3]'> <div ng-repeat='item in f(a) track by item[0]'>{{item}}</div> </body> where the function f is ...

Position the buttons away from the carousel

I am looking to use Bootstrap 4 to place full-height buttons on the left and right sides of a carousel, with the carousel being the largest element at a size of col-10. This is my current progress: @media (min-width: 768px) { /* CSS code for responsi ...

Using jQuery to manage multiple page requests on a single page

In my current project using Codeigniter, I encountered a challenge of loading multiple paginations on one page. After exploring various forums and websites, I decided to implement multiple methods and views to achieve this using jQuery. The code snippet I ...

What could be causing the read-only error in my presentation?

My website has always had a small slider that worked perfectly, but now an error message keeps popping up: Error: "myIndex" is read-only This is the JavaScript code in question: const myIndex = 0; carousel(); function carousel() { let i; const x = ...

Is there a way to expand the navbar to full width?

I am currently designing a layout that includes a side menu and a top navbar using Bootstrap 4. My goal is to have the side menu extend from top to bottom and the top navbar stretch from the side menu to the right edge of the screen. How can I achieve th ...

ReactJS is failing to render the component

Background: In my dissertation project, I made the choice to utilize React in order to incorporate a table into the webpage, allowing users to select which room they want to enter. Currently, I am using SWIG as a tempting engine to generate the table when ...

Steps to hide a div after it has been displayed once during a user's session

After a successful login, I have a div that displays a success message and then hides after 4 seconds using the following JavaScript code: document.getElementById('success').style.display = 'none'; }, 4000); While this functionality wo ...