Search code examples
htmlcssword-wrap

CSS word-wrap does not work in table


I need to create a table with fixed headers, a table-body scrollable on the Y-axis (but not on the X-axis) and columns of a fixed width.

I found this answer to my problem: https://stackoverflow.com/a/17585032/6033166

It works like a charm (many thanks!) and I started to base my code on this answer. I added table-layout: fixed, word-wrap: break-word and overflow-y: auto; overflow-x: hidden; in order to tackle my additional requirements.

However one problem remains. If a very long text is entered into a table cell, without (or with very few) blank spaces, no line breaks will be added, but instead the width will change by brute force, the table row is "making room" for the one big entry, pushing the other cells to the sides.

I have found answers and suggestions on SO which say that I could add the <wbr> tag to the content and thus suggest the browser when to make line-breaks. The problem here is that the content is retrieved from a database (via C#) and would then need to be processed before displaying, which is a step I would like to skip, if possible. If there is any way, I would like to keep this in CSS. However, I am also very open to other solutions if there is no other possibility.
I tried also break-all, same result.

This is my current CSS for the table:

    table.tableSection {
    display: table;
    width: 100%;
    table-layout: fixed;
    word-wrap: break-word;
}
table.tableSection thead, table.tableSection tbody {
    float: left;
    width: 100%;
}
table.tableSection tbody {
    overflow-y: auto;
    overflow-x: hidden;
    height: 100px;
}
table.tableSection tr {
    width: 100%;
    display: table;
    text-align: left;
}
table.tableSection th, table.tableSection td {
    width: 33%;
}

And this is the HTML code:

<table class="tableSection">
<thead>
    <tr>
        <th>1</th>
        <th>2</th>
        <th>3</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>Text</td>
        <td>Text</td>
        <td>Text</td>
    </tr>
    <tr>
        <td>Text</td>
        <td>This does work very well with blank spaces. The text has no limitation in size, line breaks will simply be added.</td>
        <td>Text</td>
    </tr>
    <tr>
        <td>Text</td>
        <td>This_does_not_work_sadly,_which_is_a_huge_problem,_since_blank_spaces_are_not_permitted_as_word_delimiters.</td>
        <td>Text</td>
    </tr>
    <tr>
        <td>Text</td>
        <td>Text</td>
        <td>Text</td>
    </tr>
</tbody>

Here is a link to my jsfiddle to demonstrate what I mean: https://jsfiddle.net/Fi_Vi/bmc7r8rz/3/


Solution

  • Add the following code to your td's CSS style table.tableSection th, table.tableSection td { ... }

    word-break: break-all;
    

    Here is the updated fiddle: https://jsfiddle.net/bmc7r8rz/8/