参考资料

  1. HTML DOM 返回文档中的图像数
  2. HTML DOM 返回表单中的enctype属性的值
  3. HTML DOM document.write() 方法
  4. HTML DOM 返回当前的文件和链接的文档之间的关系
  5. HTML DOM 改变一个iframe的src
  6. HTML DOM 返回一个锚的名字 实例
  7. HTML DOM对单个单元格的内容垂直对齐
  8. HTML DOM 返回文档的最后一次修改时间 实例

HTML DOM单元格内容水平对齐

HTML DOM 单元格内容水平对齐

介绍

HTML表格单元格内容可以通过多种方式进行水平对齐,主要使用align属性或CSS样式来控制。

主要标签和属性

  • <td align="value"> - 表格数据单元格

  • <th align="value"> - 表格标题单元格

  • style="text-align: value" - CSS样式方式

对齐值

  • left: 左对齐

  • right: 右对齐

  • center: 居中对齐

  • justify: 两端对齐

用法示例

HTML属性方式

<table>
  <tr>
    <td align="left">左对齐</td>
    <td align="center">居中对齐</td>
    <td align="right">右对齐</td>
  </tr>
</table>

CSS样式方式

<table>
  <tr>
    <td style="text-align: left">左对齐</td>
    <td style="text-align: center">居中对齐</td>
    <td style="text-align: right">右对齐</td>
  </tr>
</table>

功能扩展

使用CSS类

<style>
  .left { text-align: left; }
  .center { text-align: center; }
  .right { text-align: right; }
</style>

<table>
  <tr>
    <td class="left">左对齐</td>
    <td class="center">居中对齐</td>
    <td class="right">右对齐</td>
  </tr>
</table>

整列对齐

<style>
  td:nth-child(1) { text-align: left; }
  td:nth-child(2) { text-align: center; }
  td:nth-child(3) { text-align: right; }
</style>

<table>
  <tr>
    <td>左对齐</td>
    <td>居中对齐</td>
    <td>右对齐</td>
  </tr>
</table>

注意事项

  • align属性在HTML5中已不推荐使用,建议使用CSS的text-align属性

  • 对齐效果会继承到单元格内的所有内容,包括文本和其他内联元素