I have a table within a webpage I'm building, where either the left or right columns (but not both) will have some fairly-long text (a handful of words). The table has two columns - the first column is left-aligned, and the second column is right-aligned. Here's a simplified version of my table:
<table>
<tr>
<td>Some rather long text</td>
<td class=right-align>Short text</td>
</tr>
<tr>
<td>Text</td>
<td class=right-align>Some very long piece of text</td>
</tr>
</table>
It also has a small bit of CSS that goes with it:
.right-align {
text-align: right;
}
table {
width: 100%;
}
At a reasonable width, it looks fine:
Unfortunately, if I shrink the window, the text wraps:
Is there a way to have the text proceed through the "column separator", and allow that border to be at a different place for each row? There would be room for each row to take up only one line if the "column separator" could be different for each row. I am not using any libraries, just CSS + HTML.
I'm looking for it to do something like this (drawing made in MS Paint)
If you need to use html <table>
syntax, create one table for each row of data, your CSS will work.
Alternatively use e.g. <div>
tags with CSS flexbox layout applying flex: auto
to the col
class, to distribute the available space.
Empty space distribution is handled differently by either approach. Check their behavior in the snippet below to see how the empty space distribution is handled when resizing the available document width (browser window). Obviously text will start wrapping, once the width of a cell/div is fully occupied.
I've added colored borders/background and removed the table's cellpadding and cellspacing to better illustrate the behavior of the 2 examples.
.right-align {
text-align: right;
}
table {
width: 100%;
}
td {
border: 1px solid red;
}
.wrap {
width: 100%;
background-color: gold;
margin-top: 10px;
}
.row {
display: flex;
}
.col {
border: 1px solid blue;
flex: auto;
}
.col:last-of-type{
text-align: right;
}
<table cellpadding="0" cellspacing="0">
<tr>
<td>Some rather long text</td>
<td class=right-align>Short text</td>
</tr>
</table>
<table cellpadding="0" cellspacing="0">
<tr>
<td>Text</td>
<td class=right-align>Some very long piece of text</td>
</tr>
</table>
<table cellpadding="0" cellspacing="0">
<tr>
<td>Some even more rather long text</td>
<td class=right-align>txt</td>
</tr>
</table>
<div class="wrap">
<div class="row">
<div class="col">
Some rather long text
</div>
<div class="col">
Short text
</div>
</div>
<div class="row">
<div class="col">
Text
</div>
<div class="col">
Some very long piece of text
</div>
</div>
<div class="row">
<div class="col">
Some even more rather long text
</div>
<div class="col">
txt
</div>
</div>
</div>
No, not with classic html tables. You will have to use grid or flexbox to achieve your desired effect.