Unable to auto set width of HTML columns based on the content

Viewed 40

I have HTML table. I want to auto set the width of table columns , which changes as per the content. For example in below image you can see ID column content has to come in a single line, but even though width is set to auto , its not working here. Am i missing out on something? Please find my code below: CSS:

<style>
    table {
        font-family: arial, sans-serif;
        border-collapse: collapse;
        width: 100%;
    }

    td, th {
        border: 1px solid #dddddd;
        text-align: left;
        padding: 8px;
        width: auto !important;
        overflow: hidden;
    }

    tr:nth-child(even) {
        background-color: #dddddd;
    }
</style>

html table:

<table>
    <thead>
        <tr>
            <th></th>
            <th>ID</th>
            <th>Company Name</th>
            <th>Address</th>
        </tr>
    </thead>
    <tbody>

            @foreach (Models.UTP utpResult in lstUtpResult.utp)
            {
          <tr>
            <td>
                <input value="1" id="type_radio_1" name="type_radio" type="radio" />
            </td>
            <td>@utpResult.id</td>
            <td>@utpResult.companyName</td>
            <td>@utpResult.address.street.Line1, 
            @utpResult.address.city,
            @utpResult.address.zip.code,
            @utpResult.address.country.name
            </td>
             
          </tr>
             
           }    
            </tbody>
</table>

ID Text should fit into to a single line but its not.output image

2 Answers

Try using white-space: nowrap; for the id field

p.a {
  white-space: nowrap;
}
<h2>white-space: nowrap:</h2>
<p class="a">
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
</p>

You can try using whitespace: nowrap for your td, th style, if it just overflows out of it's container even with auto sizing you can try width: fit-content.

Related