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

Having trouble getting the img src to work in Django 2.1 template?

I'm having trouble displaying images in my Django template file. Despite uploading the images to media static files, they do not appear on the template. When I click on the image link in the Django admin page, it shows a "Page not found(404)" error me ...

Error: The specified object does not contain the 'tableRow' method

I am currently working on a contacts book project and I need a table to update as the user inputs data. However, I keep encountering an error related to 'tableRow'. I have tried changing function names and other solutions but haven't been ab ...

Tips for avoiding a button reverting to its original state upon page refresh

I have a button with the ID #first that, when clicked, is replaced by another button with the ID #second. However, if I refresh the page after clicking on the second button, it goes back to displaying the first button. Is there a way to make sure that th ...

Bringing in Sequentially Arranged HTML Content using Asynchronous JavaScript Integration

I have a collection of separate HTML files with small content snippets that are loaded through AJAX and .get(). I want to display the content in an orderly fashion without relying on async: false in my AJAX call, as it is no longer recommended. With the si ...

Optimal approaches for managing form processing duties

What is the most effective approach to handle form processing? In my situation, I typically follow these steps: If the user has not submitted the form, Display the form Otherwise, If there are any form errors, Show error messages Display the form ...

The copyright (©) symbol is unresponsive to rotation

Why can't I rotate the © character? Am I missing something? .copy { font-size: 12px; font-family: Arial; writing-mode: vertical-rl; text-orientation: mixed; transform: rotate(180deg); } <span class="copy">&copy; This is not ...

Including new styles in CKEDITOR.stylesSet that pertain to multiple elements

My idea involves creating a unique bullet list style with two specific features: a. A blue arrow image replacing the standard list icon b. Very subtle dotted borders above and below each list item. I am looking to incorporate this design into CKEditor t ...

The vertical menu was added, but the text did not align properly

I pasted a sidebar from a different source https://i.stack.imgur.com/jkYWz.png My goal is to have the text appear at the top of the page, similar to this example https://i.stack.imgur.com/1aR5s.png After adding this line, my text is displaying at the b ...

Leverage CSS to create a hover effect on one element that triggers a change in another

How can I use pure CSS to make an image appear when hovering over text? HTML <h1 id="hover">Hover over me</h1> <div id="squash"> <img src="http://askflorine.com/wp-content/uploads/2013/10/temp_quash.jpg" width="100%"> </div&g ...

I am having trouble viewing an image on my screen

I am trying to add an icon to the left side of my "Skriv ut" text, but unfortunately it is not displaying correctly. This is how I want it to look: https://i.stack.imgur.com/6jcne.png Here is the code snippet I am using: <div class="col-md-4 col-md-o ...

What could be causing my CSS relative positioning to malfunction?

I am struggling to adjust the positioning of my divs using relative and absolute properties. Any advice on how to resolve this issue would be greatly appreciated. Thank you. Example Code: <div id="game"><img src="gta-game.jpg" height="100" width ...

Blurring the background creates an "inset shadow" problem when transitioning

Problem: Strangely, when using Backdrop-filter: blur(Xpx); during a transition as shown below, unexpected "inset Shadows" mysteriously appear until the end of the transition. https://i.stack.imgur.com/uij7F.gif Illustration of the Issue Using jsfiddle Sp ...

What is the proper file format for a form action in CSS?

What I Currently Have: In my Index.html file, there are a total of 4 form elements including text fields and a dropdown. Upon submission by the user, the data is processed in confirm.html using a separate JavaScript file for formatting before being displa ...

When attempting to use the .split method, an error is thrown stating that addEventListener is not

I'm attempting to create a table that automatically fills in the next input when I select options from MySQL. However, when I run this code, I get an error saying "addEventListener is not a function." I'm not very familiar with JavaScript, so I&a ...

Issues arising from the arrangement of the menu bar

I created a navigation bar using an unordered list (ul) with list items (li). However, I encountered an issue where the items were displaying in reverse order until I applied the following CSS: .nav-bar .btn{ float: left; } .nav-bar u ...

styling multiple elements using javascript

Recently, I created a jQuery library for managing spacing (margin and padding). Now, I am looking to convert this library to pure JavaScript with your assistance :) Below is the JavaScript code snippet: // Useful Variables let dataAttr = "[data-m], [d ...

The collapsible HTML menu is malfunctioning

Can anyone assist me? I'm having trouble with the collapsible menu on my website not showing all three lists when clicked. I am using the following script link: src="http://code.jquey.com/jquery-1.11.2.min.js", or perhaps I have linked it incorrectly ...

Finding attributes with spaces in their values using XPath

Is there a way to select an attribute with spaces in xpath? I am currently trying to select a checkbox attribute named "checked type". I have experimented with //[@checked type], //[@checked-type], //[@checked_type], and //[@checked\stype], but none ...

Bootstrap 4 and Angular 7 application experiencing issues with toggle button functionality in the navigation bar

I am currently working with Angular7 and Bootstrap4. I am attempting to integrate a navbar into my application, but I am facing an issue where the toggle button does not work when the navbar is collapsed. It is important for me to mention that I do not wa ...

Can you target an 'input' field that is within a component conditionally rendered using 'v-if'?

Imagine this vue.js template code: <div v-if="y===0"> <input ref="textbox">{{textbox}}</input> </div> In the scenario where y is data retrieved asynchronously, Is there a way to direct focus to the 'input' element onc ...