Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is such alignment achievable without <table>?

The wanted result

My goal is an alignment as shown in the attached image (the fields on the left may have any width, but the ones on the right should begin at the same X coordinate).

Right now I am using a simple table code to achieve this:

<table><tr>
<td>Left1</td><td>Right 1</td></tr>
<tr><td>Left 2</td><td>Right 2</td></tr></table>

However, I've heard that using tables is generally bad. Is there a way I could achieve the same design using CSS? The website is being designed for mobile devices which might not support fancy CSS, so the code must be as simple as possible.

EDIT: since I still occasionally get a notification on this question from people who (presumably) are just starting out with HTML like I was when I made it, please refer to the accepted answer by B T as this is by far the best way to achieve this functionality. The question suggested as a "possible duplicate" (31 May 2016) does not currently offer the table-row/table-column CSS-based approach and requires you to do guess work.

like image 435
AM- Avatar asked Jun 13 '12 18:06

AM-


1 Answers

I found a much easier way to do this by accident. Say you have the following:

<div class='top'>
  <div>Something else</div>
  <div class='a'>
    <div>Some text 1</div>
    <div>Some text 2</div>
  </div>
  <div class='a'>
    <div>Some text 3</div>
    <div>Some text 4</div>
  </div>
</div>

You can align Some text 1 and Some text 2 using css table display styling like this:

.a {
  display: table-row;
}
.a div {
  display: table-cell;
}

The coolest thing is that as long as the 'top' div is NOT styled display: table, then other things like "Something else" can be ignored in terms of alignment. If the 'top' div IS styled display: table, then "Some text 1" will be aligned with "Something else" (ie it treats all its children like table rows, even if they have a different display style).

This works in Chrome, not sure if its supposed to behave this way, but I'm glad it works.

  .a {
      display: table-row;
    }
    .a div {
      display: table-cell;
    }
   <div class='top'>
      <div>Something else</div>
      <div class='a'>
        <div>Some text 1</div>
        <div>Some text 2</div>
      </div>
      <div class='a'>
        <div>Some text 3</div>
        <div>Some text 4</div>
      </div>
    </div>
like image 69
B T Avatar answered Sep 25 '22 00:09

B T