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

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>
    
asked by anonymous 23.05.2014 / 19:52

2 answers

4

As already mentioned by @Andorinha, first of all let's change id s to class :

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

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

.cabecalho {text-align: center}
    
23.05.2014 / 21:56
3

As @bfavaretto said in comment , correcting the html:

Preview response here

And it is also invalid to use the id cabecalho for all <th> change 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 multiple elements, here Class e Ids

    
23.05.2014 / 20:11