RudziankoŇ≠ RudziankoŇ≠ - 3 months ago 5
CSS Question

CSS: Align column in table

Sorry for dumb question. I am new to css. I have following UI:

enter image description here

I have following code:

<div class="row centered-form center-block">
<div class="container col-md-10 col-md-offset-1">
<table class="table">
<tr>
<td>
<h4><span class="label label-default">Hello</span></h4>
</td>
<td>
<h4><span class="label label-success">World</span></h4>
</td>
</tr>
<tr>
<td>
<h4><span class="label label-default">Hello Hello</span></h4>
</td>
<td>
<h4><span class="label label-success">World World</span></h4>
</td>
</tr>
<tr>
<td>
<h4><span class="label label-default">Hello Hello Hello</span></h4>
</td>
<td>
<h4><span class="label label-success">World World World</span></h4>
</td>
</tr>
</table>

<br/>

<div class="row centered-form center-block">
<div class="container col-md-10 col-md-offset-1">
<div class="form-inline">
<div class="form-group" style="width: 40%;">
<button class="btn btn-default">
Hello
</button>
</div>
<div class="form-group" style="width: 40%;">
<button class="btn btn-default">
World
</button>
</div>
</div>
</div>
</div>
</div>
</div>


I tried different approaches and didn't succeed. I meet align problems all the time. Please show me effective way of managing alignments in CSS. I would like to align everything by green lines, accordingly left column is
right-aligned
and right column
left-aligned
.

Answer

I agree with Pete's comment that tables shouldn't be used for layout but if you continue then you can use the following styles:

table {
  width: 100%;
}
td:nth-child(odd) { /* every first column in the 2 column table */
  padding-right: 50px;  /* this is for that gap down the middle */
  text-align: right; /* align the column to the right */
}
td:nth-child(even) { /* every second column in the 2 column table */
  padding-left: 50px; /* this is for that gap down the middle */
  text-align: left; /* align the column to the left */
}
td {
  width: 50%; /* equal width columns */
  box-sizing: border-box;
}
<table class="table">
  <tr>
    <td>
      <h4><span class="label label-default">Hello</span></h4>
    </td>
    <td>
      <h4><span class="label label-success">World</span></h4>
    </td>
  </tr>
  <tr>
    <td>
      <h4><span class="label label-default">Hello Hello</span></h4>
    </td>
    <td>
      <h4><span class="label label-success">World World</span></h4>
    </td>
  </tr>
  <tr>
    <td>
      <h4><span class="label label-default">Hello Hello Hello</span></h4>
    </td>
    <td>
      <h4><span class="label label-success">World World World</span></h4>
    </td>
  </tr>
</table>

Comments