Html 在表格单元格中居中文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7641130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Center text in table cell
提问by Hyman Stevens
I can't seem to find the answer to my issue. I have a table with two rows and two columns (like the code shown below), how do I center align the text in specific cells. I would like to center align the text in one or two of the cells - not all the cells.
我似乎无法找到我的问题的答案。我有一个两行两列的表格(如下所示的代码),如何将特定单元格中的文本居中对齐。我想将一两个单元格中的文本居中对齐 - 不是所有单元格。
<div style="text-align: center;">
<table style="margin: 0px auto;" border="0">
<tbody>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
</tr>
<tr>
<td>Cell 3</td>
<td>Cell 4</td>
</tr>
</tbody>
</table>
</div>
回答by C???
I would recommend using CSS for this. You should create a CSS rule to enforce the centering, for example:
我建议为此使用 CSS。您应该创建一个 CSS 规则来强制居中,例如:
.ui-helper-center {
text-align: center;
}
And then add the ui-helper-center
class to the table cells for which you wish to control the alignment:
然后将ui-helper-center
类添加到您希望控制对齐的表格单元格中:
<td class="ui-helper-center">Content</td>
EDIT: Since this answer was accepted, I felt obligated to edit out the parts that caused a flame-war in the comments, and to not promote poor and outdated practices.
编辑:既然这个答案被接受了,我觉得有义务编辑掉评论中引起激烈争论的部分,并且不提倡不良和过时的做法。
See Gabe's answerfor how to include the CSS rule into your page.
有关如何将 CSS 规则包含到页面中的信息,请参阅Gabe 的回答。
回答by Gabe
How about simply (Please note, come up with a better name for the class name this is simply an example):
简单怎么样(请注意,为类名想出一个更好的名字,这只是一个例子):
.centerText{
text-align: center;
}
<div>
<table style="width:100%">
<tbody>
<tr>
<td class="centerText">Cell 1</td>
<td>Cell 2</td>
</tr>
<tr>
<td class="centerText">Cell 3</td>
<td>Cell 4</td>
</tr>
</tbody>
</table>
</div>
Example here
示例在这里
You can place the css
in a separate file, which is recommended.
In my example, I created a file called styles.css
and placed my css
rules in it.
Then include it in the html document in the <head>
section as follows:
您可以将css
放在单独的文件中,这是推荐的。在我的示例中,我创建了一个名为的文件styles.css
并将我的css
规则放入其中。然后将其包含在该<head>
部分的html文档中,如下所示:
<head>
<link href="styles.css" rel="stylesheet" type="text/css">
</head>
The alternative, not creating a seperate css file, not recommended at all...
Create <style>
block in your <head>
in the html document. Then just place your rules there.
替代方案,不创建单独的 css 文件,根本不推荐...在 html 文档中创建<style>
块<head>
。然后把你的规则放在那里。
<head>
<style type="text/css">
.centerText{
text-align: center;
}
</style>
</head>