How to center the <th> header of an HTML table with css?

Asked

Viewed 8,336 times

1

My table:

<table id="tabela">
    <th id="cabecalho" >Ação</th>
    <tr id = "linAcao" >    
        <td><a href="#"><img src="Acao.jpg" title=""/></a></td>
        <td></td>
    </tr>

    <th id="cabecalho" >Comedia</th>
    <tr id = "linComedia">
        <td><a href="#"><img src="Comedia.jpg" title=""/></a></td>
        <td></td>
    </tr>

    <th id="cabecalho" >Terror</th> 
    <tr id = "linTerror" > 
        <td><a href="#"><img src="Terror.jpg" title=""/></a></td>
        <td></td>
    </tr>

    <th id="cabecalho" >Drama</th>
    <tr id = "linDrama" > 
        <td><a href="#"><img src="Drama.jpg" title=""/></a></td>
        <td></td>
    </tr>

    <th id="cabecalho" >Romance</th>
    <tr id = "linRomance" > 
        <td><a href="#"><img src="Romance.jpg" title=""/></a></td>
        <td></td>
    </tr>
</table>
  • What’s the mistake you’re making?

  • 3

    Your HTML is invalid, <th> needs to be inside a <tr>.

2 answers

5


As already mentioned by @Andorinha, first of all we will exchange the ids for class:

...
<th class="cabecalho" >Ação</th>
...
<th class="cabecalho" >Comédia</th>
... etc

Although most default browsers centralize the th, this is not guaranteed to always happen (even by a possible previous definition in another css). Thus, the ideal is to add an explicit entry in the css to ensure this:

.cabecalho {text-align: center}

3

As @bfavaretto said in commenting, fixing the html:

Response in visualization here

Also invalid to use id cabecalho for all the <th> switch to class:

<table id="tabela">

    <tr id = "linAcao" >    
        <th class="cabecalho" >Ação</th>
        <td><a href="#"><img src="Acao.jpg" title=""/></a></td>
        <td></td>
    </tr>


    <tr id = "linComedia">
        <th class="cabecalho" >Comedia</th>
        <td><a href="#"><img src="Comedia.jpg" title=""/></a></td>
        <td></td>
    </tr>


    <tr id = "linTerror" > 
        <th class="cabecalho" >Terror</th> 
        <td><a href="#"><img src="Terror.jpg" title=""/></a></td>
        <td></td>
    </tr>


    <tr id = "linDrama" > 
        <th class="cabecalho" >Drama</th>
        <td><a href="#"><img src="Drama.jpg" title=""/></a></td>
        <td></td>
    </tr>


    <tr id = "linRomance" > 
        <th class="cabecalho" >Romance</th>
        <td><a href="#"><img src="Romance.jpg" title=""/></a></td>
        <td></td>
    </tr>
</table>

See why not use the same ID for various elements, here Class and Ids

Browser other questions tagged

You are not signed in. Login or sign up in order to post.