<style> /* 将表格内所有单元格的文本居中 */ table td, table th { text-align: center; } /* 某个特定单元格右对齐 */ .right-aligned-cell { text-align: right; } </style> <table> <tr> <td>默认左对齐</td> <td style="text-align: right;">行内右对齐</td> <th>标题居中</th> </tr> <tr> <td class="right-aligned-cell">类选择器右对齐</td> <td>普通文本</td> <td><p style="text-align: justify;">这是一段尝试两端对齐的文本,看看它在表格单元格中的表现如何。通常需要多行文字才能看出效果。</p></td> </tr> </table>
<style> table { height: 200px; /* 为了演示垂直对齐,给表格一个高度 */ width: 100%; border-collapse: collapse; } td, th { border: 1px solid #ccc; height: 80px; /* 给单元格一个高度 */ } .top-aligned { vertical-align: top; } .middle-aligned { vertical-align: middle; } .bottom-aligned { vertical-align: bottom; } </style> <table> <tr> <td class="top-aligned">顶部对齐的文本</td> <td class="middle-aligned">垂直居中对齐的文本</td> <td class="bottom-aligned">底部对齐的文本</td> </tr> <tr> <td class="top-aligned">更多内容<br>多行文本</td> <td class="middle-aligned">更多内容<br>多行文本</td> <td class="bottom-aligned">更多内容<br>多行文本</td> </tr> </table>
<style> .my-table { width: 100%; border-collapse: collapse; } .my-table td, .my-table th { border: 1px solid #ddd; padding: 8px; height: 100px; /* 为了看出垂直对齐效果,给单元格一个固定高度 */ vertical-align: middle; /* 核心:垂直居中 */ text-align: center; /* 顺便也水平居中 */ } </style> <table class="my-table"> <tr> <th>标题一</th> <th>标题二</th> <th>标题三</th> </tr> <tr> <td>短文本</td> <td>这是一段相对较长的文本,用来测试垂直居中对齐的效果,看看它在单元格中是否能很好地居中显示。</td> <td>另一个短文本</td> </tr> </table>
<style> .justified-cell { text-align: justify; /* 为了看到效果,可能需要限制宽度并增加内容 */ width: 150px; } </style> <table> <tr> <td class="justified-cell"> 这是一段需要两端对齐的文本,看看它在单元格中的表现,文字会尽可能填充整个宽度。 </td> </tr> </table>
<style> .flex-cell { display: flex; align-items: center; /* 垂直居中所有子项 */ justify-content: space-between; /* 子项之间平均分布空间 */ border: 1px solid #ccc; padding: 10px; } .icon { /* 假设是图标 */ margin-right: 10px; } .button { /* 假设是按钮 */ margin-left: 10px; } </style> <table> <tr> <td class="flex-cell"> <span class="icon">?</span> <span>这是一个灵活对齐的单元格内容</span> <button class="button">操作</button> </td> </tr> </table>
<style> .padded-cell { padding: 15px 20px; /* 上下15px,左右20px内边距 */ text-align: right; } </style> <table> <tr> <td class="padded-cell"> 右对齐且有更多内边距的文本。 </td> </tr> </table>
<style> .no-wrap-cell { white-space: nowrap; /* 不换行 */ overflow: hidden; /* 溢出部分隐藏 */ text-overflow: ellipsis; /* 溢出时显示省略号 */ text-align: center; /* 文本居中 */ max-width: 100px; /* 限制单元格宽度 */ } </style> <table> <tr> <td class="no-wrap-cell"> 这是一个非常非常长的文本,它应该不会换行,并且会显示省略号。 </td> </tr> </table>
以上就是如何设置HTML表格中文本的对齐方式?有哪些属性?的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号