I found your Q&A while doing research for the same problem: getting text inside a table cell to align right and overflow to the left.
I strongly agree with you on not using dir:rtl
as mentioned e.g. in this SO answer. Besides the practical disadvantages with regards to puctuation: dir
is not meant for this problem!
In your solution, the height issue is caused by the absolute positioning of the inner div: it is placed outside the flow and thus takes no height.
I did get 'right align' to work using floats and I'm happy to share this minimal example here for anyone who may need it. I also have a 'bonus' solution for the center-case.
td {
width: 8em;
max-width: 8em;
border: 1px solid #000;
}
div.fix_right {
float: right;
white-space: nowrap;
text-align: right;
overflow: visible;
background-color: #ddd;
/* and to obscure the contents of the cell on the left: */
position: relative;
}
div.fix_center_a {
position: relative;
left: 50%;
display: inline-block;
}
div.fix_center_b {
position: relative;
display: inline-block;
margin-left: -50%;
white-space: nowrap;
/* and to obscure the contents of the cell on the left: */
background-color: #ddd;
}
<table>
<tr>
<td>some text here</td>
<td>
<div class="fix_right">align right</div>
</td>
<td>some text here</td>
</tr>
<tr>
<td>some text here</td>
<td>
<div class="fix_right">do align and overflow right</div>
</td>
<td>some text here</td>
</tr>
<tr>
<td>some text here</td>
<td>
<div class="fix_center_a">
<div class="fix_center_b">centered text, extending to the left and right</div>
</div>
</td>
<td>some text here</td>
</tr>
</table>
Align to the right
I think the key in this solution is to use the combination of float
in the div
and max-width
in the td
.
The relative positioning and bg-color are needed in order to let the contents 'obscure' the contents of the column(s) to the left. If these left columns are empty anyway, this is not even needed.
Center
This solution (unfortunately) needs an additional layer of non-semantic div, but it works as follows:
The td
is left alone so that it may get a border etc. Note that the border shows that the cell itself is not expanding, only the contents overflow it.
The first div
(fix_center_a
) gets us in the middle of the cell and gets us the total width needed for the content.
The second div
(fix_center_b
) just shifts the content 50% of the total width (from fix_center_a
) to the left, thus centering the content.
(Because of the relative positioning of the first div
, the content already obscures the content of the left and right cells if you apply a background-color on the fix_center_b
.)