Skip to content Skip to sidebar Skip to footer

How To Center Text In Table Cell When It Overflow?

I would like to center some text in the middle of my cell but the text is bigger than the width of the cell so it overflow to the right. Would it be possible to make it overflow fr

Solution 1:

Actually there's a CSS only way and it's very simple:

Demo http://jsfiddle.net/p5wg8yyc/9/

.toCenter {
    display: inline-block;
    position: relative;
    margin-left: 50%;
    -webkit-transform: translateX(-50%);
    transform: translateX(-50%);
}

Solution 2:

Simple css fix : http://jsfiddle.net/p5wg8yyc/8/

HTML:

<tr>
    <td><span>AB</span></td>
    <td><span>SomeVeryBigTextThatDoesNotFit</span></td>
    <td></td>
</tr>

CSS:

td span{
    margin-left:-50%;
    margin-right:-50%;    
}

Solution 3:

Here's what you need

           table, td{
    border:1px solid black;
}

table{
    table-layout: fixed;
    width:500px;
    border-collapse: collapse;
    table-layout:fixed;
}

td{
    word-wrap:break-word;
    text-align:center;
    color:red;
}
       <table>
    <thead>
        <tr>
            <th>Left</th>
            <th>Center</th>
            <th>Right</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td></td>
            <td>SomeVeryBigTextThatDoesNotFit</td>
            <td></td>
        </tr>
    </tbody>
</table>
 

Solution 4:

EDIT: Left here for posterity, but Arbel's CSS-only answer is a much better approach.


Some JavaScript is probably required to make this happen. I've posted an example here using jQuery 1.11 which really just helps with selecting the elements and getting/setting their properties:

http://jsfiddle.net/sd8xw5d6/1/

Basically just getting the width of the cell and the text and adjusting the positioning:

$(function() {
    var textWidth = $(".overflowtext").width();
    var tdWidth = $(".overflowcell").width();
    $(".overflowtext").css("margin-left", tdWidth/2 - textWidth/2);
});

Note that while this works, you'd still need to account for window resizes and adjust as necessary, as the sizing will only work for the original window size, but hopefully this will get you started.


Post a Comment for "How To Center Text In Table Cell When It Overflow?"