如何在CSS中对齐表格

时间:2019-05-20 02:39:27

标签: html css

我需要将表格右对齐。我使用了float:right,但仍然无法正常工作。还有其他选择吗?

<table style="text-align:right; width:100%; float:right;">
  <td class="route-summary">
    <tr>
      <th>Drop No.</th>
      <th>Route Name/Destination</th>
    </tr>
  </td>
</table>

如您所见,text-align:rightfloat:right都不起作用。

4 个答案:

答案 0 :(得分:0)

你好,我想如果要使表格对齐,则应设置table而不是td

的样式

Changed table width to show perfectly right align & right floating table

 <table class="route-summary"style="text-align:right; width:80%; float:right;">
   <tr>
    <th>Drop No.</th>
    <th>Route Name/Destination</th>
   </tr>
 </table>

答案 1 :(得分:0)

要将整个表格向右对齐,请将其包装在div中,为表格赋予一个宽度,然后使用flexbox将各项向右对齐:

.parentDiv{display:flex; justify-content: flex-end;}

演示1

.flexparent{display:flex;justify-content:flex-end;}
table{width:60vw;border-collapse:collapse;}
th{border:1px solid red;}
td{border:1px solid green;}
<div class="flexparent">
  <table>
      <tr>
          <th>Drop No.</th>
          <th>Route Name/Destination</th>
      </tr>
      <tr>
          <td class="route-number">17</td>
          <td class="route-name">Paddington Station</td>
      <tr>
  </table>
</div>


要设置要右对齐的单元格数据的样式,请在th和td元素上使用CSS:

th, td{text-align:right;}

演示2

table{width:60vw;border-collapse:collapse;border:1px solid red;}
th,td{text-align:right;}
th,td{border:1px solid green;}
<table>
  <tr>
    <th>Drop No.</th>
    <th>Route Name/Destination</th>
  </tr>
  <tr>
    <td class="route-number">17</td>
    <td class="route-name">Paddington Station</td>
  <tr>
</table>


还要注意,<tr>元素分别包装<th><td>元素。 <tr><th>元素都不会放入<td>元素中(尽管可以-但不再是好的HTML-可以将整个表格插入<td>元素中) 。基本上,您的表结构应如下所示:

table
    tr
        th
        th
    /tr
    tr
        td
        td
    /tr
    tr
        td
        td
    /tr
    tr
        td
        td
    /tr
/table

参考:

Flexbox Cheatsheet

EXCELLENT Flexbox Tutorial (20 min)

今年您将花费的最好的20分钟时间是学习flexbox。当Bootstrap从Floats迁移到Flexbox时,Bootstrap会将其主版本号从Bootstrap3更改为Bootstrap4是有原因的。 这很容易!

答案 2 :(得分:0)

您的桌子位于右侧。在这里,您将表格宽度设为100%,这就是为什么它占用了整个窗口的宽度,而您却无法弄清表格的确切对齐方式。因此,我减小了桌子的宽度并设置了边框,以便您可以直观地看到桌子的对齐方式。

<table style="text-align:right; width:70%; float:right;border:1px solid black;">
      <td class="route-summary">
        <tr>
          <th>Drop No.</th>
          <th>Route Name/Destination</th>
        </tr>
      </td>
    </table>

答案 3 :(得分:0)

感谢您的信息。我正在解决问题。我只添加左边距,它被移动了。 :)

这是代码。

<td>
<div style="text-align:right; margin-left:160px; width:100%;">                  
<table class="route-summary">
<tr>                             
<th>Drop No.</th>
<th>Route Name/Destination</th>
</tr>