Flexible columns with dynamic maximum width based on percentage

After extensive research, I am turning to stackoverflow for help with a seemingly simple task that has proven difficult to achieve. I have three columns of expandable content and need them to adjust in size proportionally when one or more are expanded. Each column should have a maximum and minimum width set as either percentages or static values to prevent excessive squashing when expanding. The example code I attempted did not work due to max-width percentage limitations on table cells.

<table width="100%"><tr>
<td style="min-width:200px; max-width:60%;">Col1ExpandableContent</td>
<td style="min-width:200px; max-width:50%;">Col2ExpandableContent</td>
<td style="min-width:200px; max-width:40%;">Col3ExpandableContent</td>
</tr></table>

To address this issue without the use of frameworks or jQuery, I created a script that dynamically adjusts the maximum width of each column based on the container's width. This approach allows for smooth resizing transitions without relying on JavaScript. While this solution works for now, I am open to alternative methods that meet the specified requirements and possibly offer animated size transitions or further explanation of why percentage max-width does not work with TDs.

Answer №1

Would you like to give it a shot?

There is an example provided for only one tr td.

You need to implement each function for this specific scenario.

Give it a try, you might get some inspiration..

Cascading Style Sheets

    <style type="text/css">
        td { border: 1px solid black; }

    </style>    

JavaScript

    <script>
    function onLoadFunction(){
        if(($(".tdFirst div").text().length)<100){
            $(".tdFirst div").css('width','200px'); // minimum width
        } else if(($(".tdFirst div").text().length)>=400) {
            $(".tdFirst div").css('width','400px'); // maximum width
        } else {
            $(".tdFirst div").css('width',$(".tdFirst div").text().length+'px'); //auto adjust width 
        }
    }
    </script>

HyperText Markup Language

    <body onLoad="onLoadFunction()">
        <table>
            <tr>
                <td align="center"class="tdFirst">
                    <div>
                        Test Test Test Test Test ... (text truncated for readability)
                    </div>
                </td>
                <td><p>testing...</p></td>
            </tr>
        </table>
    </body>

Second Try

Ensure to include jQuery in your fiddle

    $('document').ready(function(){
        $(".tdFirst div").each(function(){
            if(($.trim($(this).text()).length)<50){
                $(this).css('width','20px'); // minimum width
            } else if(($.trim($(this).text()).length)>=60) {
                $(this).css('width','60px'); // maximum width
            } else {
                $(this).css('width',$.trim($(this).text()).length+'px'); //auto adjust width 
            }
        });
    });

Answer №2

To make widths dynamic using percentages and max-width, the parent element should have a specified width in pixels. This can be applied to either the table itself or a container div surrounding the table.

You can view the updated fiddle here: http://jsfiddle.net/qoaxxbqp/

In this update, both the container div and the table element have initial width settings as shown below:

<div  style="width:600px;border:2px blue solid;" >
   <table width="500px"><tr>
    <td style="min-width:100px; max-width:60%;">Col1ExpandableContent</td>
    <td style="min-width:100px;max-width:50%;">Col2ExpandableContent</td>
    <td style="min-width:100px; max-width:40%;">Col3ExpandableContent</td>
   </table>
</div>

If you only set a fixed width on the table without a parent container, or if you set a fixed width on the container div while using width:100% on the table, it is imperative to have a parent element with a fixed width (in this case, a table with % width).

I have also included jQuery hover functions to showcase the expansion effect.

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

Learn to Generate a Mathematical Quiz with Javascript

For a school project, I am tasked with developing a Math Quiz which showcases questions one at a time. The questions vary in type, including Multiple Choice, Narrative Response, Image Selection, Fill in the blank, and more. I require assistance in creatin ...

Utilizing Jquery on the client side in conjunction with a Node.js server

I am using nodejs within a docker-compose container to create a local web app. My goal is to use jquery on the client-side to load an HTML file into a div, but I'm encountering issues with it not working properly. Both the initial index.html and the n ...

Modify the color of CSS for all elements except those contained within a specific parent using jQuery

I have a color picker that triggers the following jQuery script: //event.color.toHex() = hex color code $('#iframe-screen').contents().find('body a').css('color', event.color.toHex()); This script will change the color of al ...

What is the process for assigning the value returned from an Angular HTTP request to ng-bind?

I am trying to retrieve a value from an HTTP request in AngularJS and set it as the result in a variable that is bound to ng-bind. The goal is for the value returned from the HTTP request to be displayed when text is typed into an input field. Below is th ...

Incorporate new functions through the css class name "javafx"

On my dashboard, I have 10 labels that share the same CSS class for mouse over events. Now, I want to change the button style after it is pressed and remove the mouse over effect. How can I achieve this? ...

Is there a way to use PHP to calculate the number of lines in an HTML code?

After using a WYSIWYG-editor (WordPress) to generate HTML content, I am seeking a way to display a preview of this HTML by showing only up to 3 lines of text in HTML format. For example: <p>Hello, this is some generated HTML.</p> <ol> ...

Bootstrap - Border padding excessively wide

For a project exercise using bootstrap, I'm working on recreating a page that can be found here: https://codepen.io/freeCodeCamp/full/NNvBQW I've hit a roadblock in trying to put a border around the image. Here's the code I have so far: htt ...

Resizing images using a dynamic frame size

I am in need of some assistance as I am currently facing a roadblock. My goal is to develop a picture framing tool for photos where users can specify the size of their photo, choose a colored cardboard mount, and select a frame type. My client has requeste ...

Ways to hide the value from being shown

I have integrated jscolor (from jscolor) to allow users to pick a color with an input field. However, I am facing issues in styling it as I'm unable to remove the hex value of the selected color and couldn't find any relevant documentation on av ...

Merge multiple echoes to create a single echoed string that is valid HTML

<?php // link to Google Docs spreadsheet $url='https://docs.google.com/spreadsheets/d/1_4d-MPxTUOVZbxTOlhjXv1ebTlBPQ-_JrYUlS1rqX5Q/pub?output=csv'; // open file for reading if (($handle = fopen($url, "r")) !== FALSE) { while (($data = fge ...

Creating your own personalized menu in PHP

Although I am relatively new to PHP, I have successfully developed a membership framework for my website that is fully functional. However, before diving into the design phase, there is one particular thing I am keen on achieving but unsure of how to go ab ...

Utilizing Bootstrap to create a row of four columns

I am utilizing Bootstrap 4.5.1 to showcase 4 columns, arranged in a row. Here is how my 4 columns are currently displayed: View I would like these 4 columns to be aligned in a single row without wrapping. Below is the code snippet for achieving this: ...

Replicate the ctrl+/- function through coding

While browsing with your browser, you have the ability to adjust the font size by using CTRL + + or CTRL + -. Is there a way to replicate this functionality through code, such as with JavaScript? I am looking to add buttons on my website that allow users ...

changing tooltip color in bootstrap based on the parent element

Is there a way to adjust the bootstrap tooltip background-color based on the container? For example, my header has a white background and my footer is black. #header .tooltip-inner{ background-color:fade(@grayWhite,80); } #footer .tooltip-inner{ backgro ...

Prevent typing in text box when drawer is activated by pressing a button

update 1 : After removing unnecessary files, I need assistance with https://codesandbox.io/s/0pk0z5prqn I am attempting to disable a textbox. When clicking the advanced sports search button, a drawer opens where I want to display a textbox. The toggleDra ...

The color of the progress bar in JS is not displaying properly

My work involves using jQuery to manipulate progress bars. The issue I am facing is defining standard colors that should be displayed on the progress bar based on the value received. Here is my code: var defaultSegmentColors = ['#FF6363', &ap ...

Access dynamic content from Tinymce 4.x without any manual effort

Is there a way to extract the HTML content from a tinyMCE editor and display it on a page without using the tinyMCE editor itself? I know about the getcontent() function in tinyMCE, but is there another function, parameter, or plugin that can be used to ...

Refresh table in php without the need to reload the entire page

Currently, I am retrieving data in a table from the database and have three buttons - update, delete, and an active/inactive button. Each button has its own functionality, but I need to reload the updated data in the table after any event without refreshin ...

Recalling the layout following the user's computer restart

I am creating a simple online editing tool (similar to Microsoft Outline) for coursework and I would like the outline details to be saved even if the user restarts the system. How can I achieve this? <html> <head> <title>Editor</ ...

Having trouble aligning the divs

I am currently attempting to align 3 divs next to each other on my webpage, and while I have made some progress, I am running into an issue with setting the width based on a percentage of the screen. When I try to make the total width of all three divs add ...