Search code examples
c#htmlcsscenteringtext-align

How can I get text in an HTML tr (table row) to center?


I'm building some HTML in a StringBuilder like so:

builder.Append("<tr align='center' valign='top' class=\"skyBlueBackground textAlignCenter\">");
List<String> columnHeadings = GetColumnHeadings(monthCount, _begindate);
foreach (String s in columnHeadings)
{
    if (s.Equals("Grand Total"))
    {
        builder.Append("<td align='left' valign='top' class=\"forestGreenBackground whiteText\"><b>");
    }
    else
    {
        builder.Append("<td align='left' valign='top'><b>");
    }
    builder.Append(s);
    builder.Append("</b></td>");
}
builder.Append("</tr>");

Although I've got a class for centering text:

builder.Append("</style>");
. . .
builder.Append(".textAlignCenter { text-align: center; }");
builder.Append("</style>");

...the text is aligned left; it works other than that (skyblue background), it just stays magnetized to the left:

enter image description here

What must I do to get the text to center?


Solution

  • You should either set the textAlignCenter on the TD, not the TR or change the CSS definition to:

    builder.Append(".textAlignCenter td { text-align: center; }");
    

    And you should remove the explicit "align='left'" from your TD because that will still overrule the CSS.