Center text in table cell

后端 未结 2 960
面向向阳花
面向向阳花 2021-01-07 16:37

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 w

相关标签:
2条回答
  • 2021-01-07 16:46

    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:

    <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.

    <head>
     <style type="text/css">
       .centerText{
           text-align: center;
        }
     </style>
    </head>
    
    0 讨论(0)
  • 2021-01-07 16:48

    I would recommend using CSS for this. You should create a CSS rule to enforce the centering, for example:

    .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:

    <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 answer for how to include the CSS rule into your page.

    0 讨论(0)
提交回复
热议问题