Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Table column width equal to content width

Tags:

html

css

Let's say I have a table

<table class="table">
    <thead>
        <tr>
            <th>Name</th>
            <th>Price</th>
            <th>Order Dat</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Cakes</td>
            <td>100 $</td>
            <td>2015-01-09</td>
        </tr>
        <tr>
            <td>Clouthing for Sping</td>
            <td>20000 $</td>
            <td>2015-02-09</td>
        </tr>
    </tbody>
</table>

I want my second column (Prices) to be the exact size of its header length or the longest content length in its column. I don't want it, the second column, to have that 'invisible white space' that the browser adds to the column, to make the table wider.

What I have already tried:

  1. Setting Default % or px width. This is not suitable for me, since I don't know how long will my data be.

  2. Setting table width not to 100%. This is the reason, that causes the table to stretch and add those 'white spaces' to my columns. The problem is that I need my table to be 100%, I just want one of my columns NOT to be stretched.

P.s. I'm also using bootstrap. (don't know if that helps)

EDIT:

Pictures:

http://imgur.com/a/oLsFU

like image 515
Stralos Avatar asked Oct 20 '15 11:10

Stralos


1 Answers

You will want to set the column that you want the extra width to go into to have its with of 100%. This won't actually make it a true 100%, it will just force it to be a big as possible. This will make other columns wrap though to fit that need so make sure you set the white space property to no wrap.

The CSS

.table {
    width:100%;
    white-space: nowrap;
}
.nameCol {
    width:100%;
}
.table td {
    padding: 0 5px;
}

The HTML

<table class="table">
    <thead>
        <tr>
            <th class="nameCol">Name</th>
            <th>Price</th>
            <th>Order Dat</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Cakes</td>
            <td>100 $</td>
            <td>2015-01-09</td>
        </tr>
        <tr>
            <td>Clouthing for Sping</td>
            <td>20000 $</td>
            <td>2015-02-09</td>
        </tr>
    </tbody>
</table>

Fiddle to see it in action: https://jsfiddle.net/q16dp8ja/1/

Additional notes, I also added some left right padding for readabilities sake since the columns will now be narrower on the right, also you should pick a different class than .table as it can be easily confused with table the element selector.

like image 174
Wobbles Avatar answered Sep 21 '22 15:09

Wobbles