When words are enclosed in a table cell, the fixed table layout ensures that all columns are the same size

There are times when long words in my HTML table cells need to be broken if they overflow their designated area.
To learn how to break table cell words, check out this question: Word-wrap in an HTML table
The recommended CSS style is:

style="word-wrap: break-word; table-layout: fixed; width: 100%"

If I use table-layout:fixed, the columns become equal in size. However, with a 100% width for the table and fixed layout, the columns share width equally leading to excessive height.

Check out my fiddle here: http://jsfiddle.net/mavent/Y54s9/17/

What do I need?
- The table has 2 columns, and I want the second column to be as narrow as possible.
- The width of the 2nd column shouldn't exceed the column's name.
- Column names mustn't be wrapped. < th > names should not wrap.
- The 1st column should be wide with flexible width, without fixating on a specific percentage like %60, %70, etc. though a solution using fixed column widths can be considered while ensuring responsiveness.
- The table should be responsive for mobile layouts.
- Words must be strictly wrapped if they exceed the cell width. For example, if a cell can accommodate a maximum of 40 characters but a word is 45 characters long, it should break at the 41st character.

The output should look like this on both small and large screens:

Code:

.myclass1 {
    white-space: normal;
}

.myclass2 {
    word-wrap: break-word;
    table-layout: fixed;
}

<table class="table table-striped table-condensed dataTable myclass1" id="mytable">
    <thead>
        <tr>
            <th class="sorting">header1</th>
            <th class="sorting">header2</th>
        </tr>
    </thead>
    <tbody>
        <tr class="">
            <td class="">
<span class="">Some words are generally short and easy to read
<a href="#"><i class="glyphicon glyphicon-share-alt"></i></a></span>

            </td>
            <td class="">
<span><button class="btn btn-primary btn-xs">123</button></span>

            </td>
        </tr>

    </tbody>
</table>

<hr><hr>

    <table class="table table-striped table-condensed dataTable myclass1" id="mytable">
    <thead>
        <tr>
            <th class="sorting">header1</th>
            <th class="sorting">header2</th>
        </tr>
    </thead>
    <tbody>
        <tr class="">
            <td class="">
<span class="">Some words are generally short and easy to read, butsomewordsareĞĞÜÜveryverylongIŞÖlikeethisssssGAAAAAAAAAAAAAABBBBBBBBBBBBBbbbbbCCC
<a href="#"><i class="glyphicon glyphicon-share-alt"></i></a></span>

            </td>
            <td class="">
<span><button class="btn btn-primary btn-xs">123</button></span>

            </td>
        </tr>
        <tr>
            <td>
<span>Some words are generally short and easy to read, butsomewordsare veryverylonglikeethisssssGAAAAAAAAAAAAAABBBBBBBBBBBBBbbbbbCCC
<a href="#"><i class="glyphicon glyphicon-share-alt"></i></a></span>

            </td>
            <td class="">
<span><button class="btn btn-primary btn-xs">225</button></span>

            </td>
        </tr>
    </tbody>
</table>

<hr><hr>

    <table class="table table-striped table-condensed dataTable myclass2" id="mytable">
    <thead>
        <tr>
            <th class="sorting">header1</th>
            <th class="sorting">header2</th>
        </tr>
    </thead>
    <tbody>
        <tr class="">
            <td class="">
<span class="">Some words are generally short and easy to read, butsomewordsareĞĞÜÜveryverylongIŞÖlikeethisssssGAAAAAAAAAAAAAABBBBBBBBBBBBBbbbbbCCC
<a href="#"><i class="glyphicon glyphicon-share-alt"></i></a></span>

            </td>
            <td class="">
<span><button class="btn btn-primary btn-xs">123</button></span>

            </td>
        </tr>
        <tr>
            <td>
<span>Some words are generally short and easy to read, butsomewordsare veryverylonglikeethisssssGAAAAAAAAAAAAAABBBBBBBBBBBBBbbbbbCCC
<a href="#"><i class="glyphicon glyphicon-share-alt"></i></a></span>

            </td>
            <td class="">
<span><button class="btn btn-primary btn-xs">225</button></span>

            </td>
        </tr>
    </tbody>
</table>

Answer №1

It appears that within HTML and CSS, achieving automatic word breaking in table cells is challenging without setting fixed widths for table columns and using table-layout: fixed. This makes it difficult to have one column adjust dynamically while the other fills the remaining space (when table-layout: fixed is employed).

However, there is a simple workaround using JavaScript, although it may lead to inefficiencies for larger tables and a noticeable layout change. Initially, you would not define fixed layouts or column widths, but keep the total width at 100%. This way, the browser will auto-format the table so the second column adjusts based on its content (assuming sufficient content in the other column). Then, you can retrieve the width of the second column and set it explicitly on the header cell before switching to fixed table layout.

Here is a sample code snippet:

<style>
#mytable {
    word-wrap: break-word;
    width: 100%;
}
</style>
...
<table id="mytable"
...
<script>
window.onload = function() {
  var t = document.getElementById('mytable');
  var th2 = t.rows[0].cells[1];
  th2.style.width = th2.clientWidth + 'px';
  t.style.tableLayout = 'fixed';
}
</script>

Additionally, it is important to consider proper text formatting such as hyphenation or language-specific word division for normal text. For code snippets, specific break points should be indicated if necessary, using tags like <wbr> or zero-width no-break spaces.

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

Animating Text Around a Circle Using HTML5 Canvas

Can someone please help me figure out what is wrong with this code? It's not rotating as it should, and the text looks messed up. I've been trying to solve this problem for hours but can't seem to get it right. function showCircularNameRot ...

What is the best way to have text fit perfectly into a table cell?

In my asp.net table, the first column contains captions for each row of data. The length of these captions varies, with different amounts of words in each one. I am looking to align the first letters of each caption at the beginning edge of the cells (left ...

Align the content to the right and center it within the table

One common issue I face is working with tables that contain numbers requiring right alignment to ensure the ones/tens/hundreds/thousands places line up correctly. Here's an example: 2,343 1,000,000 43 43,394 232,111 In these tables, ...

Guide to changing an image on a canvas with KineticJS

I am currently working on developing a canvas that will display a hotel floor view. I have images stored in a database which I am drawing onto the canvas using x and y coordinates from the database as reference points. However, I want to add touch events t ...

Having difficulty retrieving the Area and Range information in ChartJS

I am new to working with HTML5 and ChartJS. I have noticed two different types of declarations when attaching JS Chart Versions 1.0.1 and 2.1.1. Can you please provide some insight into this? Additionally, I am facing an issue where the stripes behind the ...

Ways to create collapsible navigation bars in your website

As someone exploring client-side development, I may be misusing the term "collapsible" in my title. What I aim to accomplish in my web application is allowing users to collapse header bars into small chevrons and expand them back when necessary. I am on t ...

What steps can be taken to resolve the issue of the <td> element not being allowed as a child of an <a> tag?

https://i.stack.imgur.com/nsdA7.png How can I address these warnings? I utilized the material UI table component and suspect that the warnings are originating from component={Link} to={/patient/${patient.id}} <TableContainer className={styles.tableCo ...

Attempting to sort through elements in JavaScript

I'm looking to filter specific films based on choices made in the dropdown menus below. <select id="filmDropdown"> <option value="0">All Films</option> <option value="1">Film 1</option> <option ...

Is there a way to create a dynamic CSS class without relying on the use of IDs?

Is there a way to create a dynamic CSS class without using an ID? $( "#mydiv" ).css( "width", $("#widthtextbox").val() ); $( "#mydiv" ).css( "height", $("#heighttextbox").val() ); I am looking to implement multiple CSS classes for this task. ...

What is the best way to generate a table with continuously updating content?

If the user input : $sgl = 2; $dbl = 0; $twn = 1; $trp = 0; $quad = 0; $price_room = 250000; I want the result looks like the picture below : https://i.sstatic.net/iQYqr.jpg I have tried the following code : <?php $sgl = 2; $dbl = 0; ...

What is the best way to loop through an array and apply classes to each element separately?

I'm currently working on a unique jQuery plugin that is designed to create dynamic lists based on any data provided. The first 6 items in the list will always remain constant, regardless of the input data. When I say constant, I mean that although th ...

Why is the image popup feature not functioning properly? What could be causing the issue?

I'm experiencing issues with the functionality of my HTML file and image popup. I've attempted to troubleshoot it multiple times without success. Here is a code snippet for reference: You can view and run the code on CodePen: Open <html> ...

How to create dynamic transition effects in modal using AngularJS

My modal includes a next button for easy navigation. Initially, the modal showcases content within: <div ng-show="step1"></div> Upon clicking the next button, the modal transitions to display different contents in 'step2' within th ...

What happens to the content within a <textarea> element if it is not enclosed between the opening and closing tags?

Here's a puzzling situation - I've entered the word Hello. into a <textarea>, and while I can see it on my screen, it doesn't show up between the opening and closing <textarea> tags. It may seem like a simple issue, but I'v ...

What could be causing the issue of Vuejs 3.3 defineModel consistently returning undefined?

I am currently working with Nuxt version 3.5.1 and Vuejs version 3.3, however, I am encountering an issue where the defineModel macro always returns undefined. I am unsure why this is happening? <template> <input v-model="count"& ...

Data not getting transmitted to Rails controller via AJAX request

My development setup includes Rails 5.2.4, coffee-rails 4.2, jquery-rails 4.4.0, and jquery-ui-rails 6.0.1. I've successfully implemented functionality that allows users to drag around and resize divs on a web page. However, I now need to save the ne ...

JavaScript code to generate a random color for the box shadow effect

Recently, I developed a function that generates random divs containing circles. The function randomly selects a border color for each circle, and this feature is functioning correctly. To enhance the appearance, I decided to add a box shadow to the circl ...

Eliminate all elements marked with a particular class when the user clicks outside of a

I am currently building upon a project that I previously started here. Essentially, what I'm doing is dynamically generating tooltip popups that appear next to a link when it is clicked. However, I now need these tooltips to close when any click even ...

There was an issue retrieving the value from the $.ajax() error function, as it returned [

After successfully receiving data from the input field and sending it to the database, everything seems to be working fine. However, when attempting to retrieve the data after sending it to the database, an error is encountered: [object HTMLInputElement]. ...

tips on customizing buttons within form groups

I have set up two separate form-groups: My goal is to click on each button within each group and toggle its style from grey to green, and vice versa. However, when I click on a button, all buttons within the group turn grey except for the one that was cli ...