views:

51

answers:

2

Is it possible to specify the width of a table column in percentages using css? Also is it possible to specify the text alignment of a specific column?

For example I have a table that has 3 columns. I would like to say

col1.width = 20%
col2.width = 40%
col3.width = 40%

col1.text-align = left;
col2.text-align = right;
col3.text-align = center;
A: 

You can do that, but your <td> widths are relative to the parent container at this point.

Babiker
How exactly would I do this? Do I have to give each td element a class? Or wrap the tds in a div and specify the width for the div? Which is the correct way to do it?
xkcd
A: 

Regarding the first question: create classes that you assign to each column. Rather simple.

The aligning of text is a bit more difficult, as you can only assign a few properties to table columns as a whole. In this case, one solution would be to use the nth-child pseudo-class, but that's a CSS 3 specific feature that's not working in any of the current versions of Internet Explorer. As this answer proposes, you can also use the + combinator to style adjacent columns. That's a CSS 2.1 feature supported by IE >= 7.

<!DOCTYPE html>
<head>
<meta charset=UTF-8>
<title>Column styling</title>
<style>
table {
    table-layout: fixed;
    width: 1000px;
}

.firstColumn {
    width: 20%;
    background: #ccc;
}

.otherColumns {
    width: 40%;
    background: #eee;
}

td       { text-align: left }
td+td    { text-align: right }
td+td+td { text-align: center }
</style>
</head>
<body>
<table>
    <col class="firstColumn">
    <col class="otherColumns">
    <col class="otherColumns">
    <tr>
        <td>bla</td>
        <td>bla</td>
        <td>bla</td>
    </tr>
    <tr>
        <td>bla</td>
        <td>bla</td>
        <td>bla</td>
    </tr>
    <tr>
        <td>bla</td>
        <td>bla</td>
        <td>bla</td>
    </tr>
</table>
</body>
</html>
Marcel Korpel