htmlcsshtml-tabletableheader

How do I dynamically size HTML table column widths to the text in the "<th>" element?


I have a some data loaded into an HTML table. Each column of the table has a table header with text in it. I want each column to have a minimum width equal to length of that text (so that it doesn't overflow/wrap). How can I do this dynamically (preferably without JavaScript, just vanilla HTML/CSS)?

I've tried setting the width, min-width and max-width of the <th> elements in the CSS, it doesn't do anything.


Solution

  • Using

    table {
                table-layout: auto;
                width: 100%;
            }
    
            th {
                white-space: nowrap;
                width: max-content;
            }
    

    should get your desired results.