topskip
topskip

Reputation: 17375

Specify width of certain columns

I have a five column layout of a table and I'd like to have the following setup

C1 S1 C2 S2 C3 (content, spacer, content, ...) where C1, C2 and C3 have the same width (unknown at the moment) and S1 and S2 have a fixed width of 44 pixels. How would I specify the widths of each of the table columns? S1 and S2 are easy:

.spacer {
    width: 44px;
}

but what about the other ones?

.contentcolumn {
    width: ???;
}

The table has a dynamic width of "100%", and I'd like to avoid the trouble making it a fixed width and doing the arithmetic myself.

http://jsfiddle.net/B35Ap/

This is my HTML:

<div style="width: 400px">
<table style="width: 100%">
    <tr>
        <td id="c1">foo </td>
        <td id="s1"></td>
        <td id="c2">bar bar</td>
        <td id="s2"></td>
        <td id="c3">baz baz baz</td>
    </tr>
</table>
</div>

And this the CSS:

tr {
     height: 40px;
}


#c1, #c2, #c3 {
    width: auto;
    background-color: yellow;
}

#s1, #s2 {
    width: 44px;
}

Which gives me:

enter image description here

But I hoped for the equal width of colums 1, 3 and 5.

Upvotes: 1

Views: 119

Answers (3)

The.Bear
The.Bear

Reputation: 5855

I know that you are using a table. I did something with a list. Maybe it can help you... jsFiddle

HTML:

<ul>
  <li>Col1</li>
  <li>Col2</li>
  <li>Col3</li> 
</ul>

CSS:

ul {
    padding: 0; 
    column-count:3;
}

Check this link CSS3 Multiple Columns

Upvotes: 1

khaverim
khaverim

Reputation: 3554

The browser calculates the width for

.contentcolumn {
    width: auto;
}

Since you have the table width at 100%, this should fill the columns as much as the browser can fit them.

Add an id to your table and use

#yourtable { display:table; table-layout: fixed;}

to force the columns to be equivalent (but maintain the spacer widths)

fiddle

Upvotes: 2

Adjit
Adjit

Reputation: 10305

You can set a specific id to each column while still keeping the class for styling.

HTML

<table>
    <tr>
        <td class="contentColumn" id="C1">C1</td>
        <td class="spacer">S1</td>
        <td class="contentColumn" id="C2">C2</td>
        <td class="spacer">S2</td>
        <td class="contentColumn" id="C3">C3</td>
    </tr>
</table>

CSS

.spacer {
    width: 44px;
}

.contentColumn {
    background-color: gray;
}

#C1 {
    width: 100px;
}
#C2 {
    width: 150px;
}
#C3 {
    width: 200px;
}

Another method would be to use the css selector :nth-child in which case your css could look something like :

td:nth-child(odd){
   /*here you can set the style of every odd column -- your content*/
}
td:nth-child(even){
   /*here you can set the style of every even column -- your spacers*/
}
td:nth-child(1){
   /*here you can set the style of your first column*/
}
td:nth-child(3){
   /*here you can set the style of your third column*/
}
etc...

Upvotes: 0

Related Questions