J. Soukup
J. Soukup

Reputation: 45

Text-align text on the left to the right and text on the right to the left

I know the title sounds complicated, but it's hard to describe - here is a fiddle.

There are two versions of the same thing I'd like to accomplish, which is that the two "columns" are supposed to be aligned to each other, but at the same time to be aligned to the left border of parent as a whole.

The red (bottom) one is the simpler version, which works unless the viewport is too slim and the text breaks on another line and the two "rows" are not in line anymore.

The blue (top) one, on the other hand, fixes the breaking problem and works as supposed to, but isn't aligned to the left of the parent (viewport) as it needs specified width to work.

Is there any solution to incorporate the best of both worlds?

Thank you.

Upvotes: 0

Views: 183

Answers (2)

PIIANTOM
PIIANTOM

Reputation: 1391

Indeed, using a table will help you to achieve this. But as you mentioned, this can be a semantic issue. Your first sample is quite interesting though as it is quite the same organization as a table (<li> can mimic <tr>, and <span> can mimic <td>).

It means that you can achieve the desired result by using the table display properties (inline-table, table-row, table-cell)

Obviously, CSS code can be

 /* first */

 ul {
   list-style: none;
   padding: 0;
   display: inline-table;
 }

 li {
   margin: 8px 0;
   display: table-row;
 }
 span{display: table-cell;}
 span.amount {
   padding-right: 16px;
   text-align: right;
   color: #999999
 }

 span.name {
   width: calc(60% - 16px);
 }

 .first {
   background-color: #dee4ec;
 }

The solution https://jsfiddle.net/piiantom/a09ezpgc/

Upvotes: 1

rkrishnan
rkrishnan

Reputation: 806

How about using an HTML table?

.cell-left {
  text-align: right;
  padding-right: 10px;
}

.cell-right {
  text-align: left;
  padding-left: 10px;
}
<table>
  <tr>
    <td class="cell-left">2</td>
    <td class="cell-right">lorem</td>
  </tr>
  <tr>
    <td class="cell-left">100</td>
    <td class="cell-right">mlipsum dolor sit</td>
  </tr>
  <tr>
    <td class="cell-left">1</td>
    <td class="cell-right">tbspamet consectetur adipiscing</td>
  </tr>
  <tr>
    <td class="cell-left">100</td>
    <td class="cell-right">gelit sed do eiusmod tempor incididunt</td>
  </tr>
  <tr>
    <td class="cell-left">½</td>
    <td class="cell-right">tsp tsput labore</td>
  </tr>
  <tr>
    <td class="cell-left">3</td>
    <td class="cell-right">tbsp tbsp tbspet dolore magna aliqua</td>
  </tr>
</table>

Upvotes: 1

Related Questions