A commonly used method to adjust the width of a table column to accommodate the size of the child element

I have a specific table width of 776 pixels with three columns. The third column has a fixed width of 216 pixels, but the widths of the other two are unknown. I want the second column to adjust its width based on its content, and whatever space is left after accounting for the third column should be allocated to the first column.

I came across a solution where the width of the column that needs to shrink is set to 1 pixel. While this does work, it feels more like a workaround than a standard practice. Is there a more conventional way to achieve the same outcome?

Below is an example of my HTML code with inline CSS:

<table style="width:776px; height:48px;">
    <tr>
        <td style="height:48px;">
            <div style="background:#f0f0f0; border:solid 2px #808080; font-size:0; margin-left:8px; text-align:center;">
                <a href="#"><h3 style="display:inline-block; font-size:20px; line-height:28px; padding:8px;">Art</h3></a>
                <a href="#"><h3 style="display:inline-block; font-size:20px; line-height:28px; padding:8px;">Events</h3></a>
                <a href="#"><h3 style="display:inline-block; font-size:20px; line-height:28px; padding:8px;">Papers</h3></a>
                <a href="#"><h3 style="display:inline-block; font-size:20px; line-height:28px; padding:8px;">Research</h3></a>
            </div>
        </td>
        <td style="vertical-align:middle; width:1px; height:48px;">
            <h3 style="margin-left:8px;"><label for="search">Search:</label></h3>
        </td>
        <td style="vertical-align:middle; width:216px; height:48px;">
            <input id="search" style="margin-left:8px; width:208px;" type="text" value="" maxlength="32">
        </td>
    </tr>
</table>

Answer №1

To easily achieve this layout, you can start by setting the width of the first cell to 100%. This will make it expand to fill the parent table's width as much as possible. Next, in the third cell, insert a content element with a width of 216px, such as a div.

Table cells will always try to adjust to fit their content. In this setup, the second cell will be squeezed in the middle according to its own content, while the third cell will adhere to the fixed 216px width, leaving the first cell to fill up the remaining space.

See Example on JsFiddle

<table>
    <tr>
        <td>1stContent</td> <!-- Fills available space -->
        <td>2ndContent</td> <!-- Squeezed in the middle -->
        <td>
            <!-- Adheres to 216px width -->
            <div class="dv3rd">
                216px
            </div>
        </td>
    </tr>
</table>

CSS:

table {
    width: 776px;
    background: silver;
}

td:nth-child(1) {
    width: 100%;
    background: red;
}

td:nth-child(2) {
    background: green;
}

td:nth-child(3) {
    background: blue;
}

.dv3rd {
    width: 216px;
}

Alternative Approach

Although tables can achieve this layout, it is recommended to avoid using them for page structure. A better approach would be to utilize CSS tables, where div elements can mimic the behavior of table and table-cell display properties.

Here's the same example implemented without tables:

See Tableless Example on JsFiddle

<div class="table">
    <div>
        1stContent
    </div>
    <div>
        2ndContent
    </div>
    <div>
        <div class="dv3rd">
            216px
        </div>
    </div>
</div>

CSS:

.table {
    width: 776px;
    background: silver;
    display: table;
}

.table > div:nth-child(1) {
    display: table-cell;
    width: 100%;
    background: red;
}

.table > div:nth-child(2) {
    display: table-cell;
    background: green;
}

.table > div:nth-child(3) {
    display: table-cell;
    background: blue;
}

.dv3rd {
    width: 216px;
}

Answer №2

I discovered the reason why this technique works by following a link shared by BoltClocks in the comments section: http://www.w3.org/TR/CSS21/tables.html#auto-table-layout

Upon further investigation, it is noted that this algorithm could potentially be inefficient as it necessitates the user agent to have full access to all table content to determine the final layout, possibly requiring more than one pass.

The determination of column widths adheres to the following methodology:

  1. Begin by calculating the minimum content width (MCW) of each cell: the content format might span multiple lines but should never exceed the cell box boundaries. If the specified 'width' (W) of the cell surpasses MCW, then W serves as the minimum cell width. In cases where 'auto' is designated, MCW automatically becomes the minimum cell width...

Solution:
Compute the minimum content width (MCW) for each cell accordingly – ensuring the formatted content remains within the confines of the cell box.

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

Challenges with incrementing in Jquery's each loop and setTimeout

http://jsfiddle.net/fxLcy/ - an example showcasing the use of setTimeout. http://jsfiddle.net/fxLcy/1/ - this demo does not include setTimeout. Although all elements are correctly positioned, I am in need of that delayed animation =/ My goal is to arrang ...

Disappearing sticky-top navbar in Bootstrap when scrolling

I'm having trouble with the navbar on my website. Currently, it sticks to the top until I scroll out of the hero-image and then disappears. I would prefer the navbar to remain present throughout the entire page. Any suggestions on how to achieve this? ...

When resizing the browser, HTML/CSS elements tend to shift positions :(

I've experimented with different position values like absolute, fixed, and static without success. Wrapping the element in a div didn't yield the desired result, so I'm seeking assistance to correct this. (If that is the solution) The issu ...

Modify the h:outputText value dynamically with the power of jQuery!

Is it possible to use jQuery to dynamically change the value of my OutputText component? This is the code snippet for my component: <h:outputText id="txt_pay_days" value="0" binding="#{Attendance_Calculation.txt_pay_days}"/> I would apprecia ...

Capable of retrieving response data, however, the label remains invisible in the dropdown menu

Upon selecting a country, I expect the corresponding city from the database to be automatically displayed in the dropdown menu. While I was able to retrieve the state response (as seen in the console output), it is not appearing in the dropdown menu. Inte ...

Maintaining Proper Header Dimensions

Having some issues with aligning my fixed widget and floating navigation. The fixed widget is not respecting the height of the floating navigation and is appearing at the top when in its fixed position. I'm currently using "Q2W3 Fixed Widget" for the ...

Button Menu in HTML

When you click the menu button, I want the text inside the class="greetings" div to change from "Welcome Jon deo" to just "G" So basically, whenever the menu button is clicked, display the letter G and hide or replace "Welcome Jon deo" Addition ...

The fixed navigation bar shows a flickering effect while scrolling at a slow pace

Currently facing a challenge with our sticky navigation. Noticing a flickering issue on the second navigation (sticky nav) when users scroll down slowly. The problem seems to be specific to Chrome and Edge, as it doesn't occur on Firefox, IE11, and S ...

Looking to have the image float after reducing the size of the windows in html?

For my webpage, I want an image to appear on the extreme left when the browser is maximized, but then move to the extreme right when the browser is minimized. I've tried using float, but it doesn't seem to be working. Any suggestions on how to ac ...

Displaying the HTML code for a dynamically generated table

Can the generated HTML code be retrieved when dynamically creating a table using v-for loops in Vue? <table> <tr> <th colspan="99">row 1</th> </tr> <tr> <th rowspan="2">row 2< ...

Setting variables in AngularJS services without encountering JavaScript undefined errors

After developing an AngularJS module, I attempted to link a service and use it to share variables across the application. While most things are functioning properly, I encountered an issue when trying to set submenu[1] to an object. The error message sta ...

Unknown identifier in the onClick function

I want to create a JavaScript function that can show or hide a paragraph when clicking on an arrow. The challenge I'm facing is that I have a list of titles generated in a loop on the server, and each title is accompanied by an arrow. Initially, the c ...

Choosing elements in HTML using jQuery from an Ajax GET response

As a programming student, I am currently working on developing a basic website using HTML, JavaScript, and jQuery for the front-end, while utilizing node.js and Express frameworks for the back-end. In my project, I have used Ajax to retrieve data and then ...

Vibrant shades of color overflow the Mui Radio

For my current web project, I am utilizing Mui for styling purposes. I am seeking guidance on how to style a radio button in a way that it appears completely filled with one color when selected. It is important that this styling method is compatible with M ...

The CSS and JS codes are not successfully integrating into the webpage

I am encountering an issue with loading CSS and JS files onto my page. My project involves PHP and Xampp. The file structure is as follows: My Site - CSS - index.css - JS - index.js - Index.php (Apologies for the lack of a folder tre ...

What is the best way to change the maxWidthLg of Material UI's .MuiContainer?

I need to remove the max-width that is set in the theme. When I look at it in Chrome and uncheck the option, it functions as desired: @media (min-width: 1280px) .MuiContainer-maxWidthLg { max-width: 1280px; } How can I achieve this? I have attempted ...

Navigate directly to a specific section on a webpage

Check out these different links: <a class="faq_text_header_jump" href="#general_questions">Questions About General Topics</a><br> <a class="faq_text_header_jump" href="how_to_use_platform">How to Use the Platform</a><br ...

What could be causing the append function to only work during the final iteration of my code?

I find myself in the position of recreating a table based on another existing one. While I am aware that this may not be the ideal approach, it is a task that has been assigned to me rather than being my own choice. My method involves iterating through ea ...

HTML forms default values preset

I need help with pre-setting the values of a dropdown menu and text box in an HTML form for my iPhone app. When the user taps a button, it opens a webview and I want to preset the dropdown menu and text field. Can someone guide me on how to achieve this? ...

Evaluating h1 content in HTML using Angular Protactor testing

I am completely new to end-to-end testing. I have a login page in my application that should be displayed to users when they log out. However, I am facing an issue with retrieving the text from a specific div element containing an h1 tag, leading to unexpe ...