How do I limit the table width to the containing element (or screen)?

后端 未结 1 1852
星月不相逢
星月不相逢 2021-01-01 17:08

I need to show tabular data using a table, but it will be within a fluid layout; I want to have a it fill the entire available width but not to expand horizonta

1条回答
  •  盖世英雄少女心
    2021-01-01 17:43

    I'm including some markup below that tests the HTML/CSS to achieve what I believe you want.

    There is a fixed-width cell style .fixedcell and fluid width cell style .fluidcell. I've set a fixed width (75px for this example) simply to illustrate things better.

    The fluid width ones have width:auto so they fill the width of the remaining table space; they also importantly have white-space:nowrap so the text doesn't expand the cell height-wise (white-space:pre works too); and finally they have overflow:hidden so the text doesn't overflow the width and make things ugly, alternatively you could set overflow:scroll for it to have a scrollbar in those cells when/if necessary.

    The table is set to be 100% width so it will expand to fit the screen/etc as needed. And the important thing regarding the table's style is the table-layout:fixed, this makes the table adhere to the layout of the page rather than auto-sizing itself based on its own content (table-layout:auto).

    I also added some borders to help illustrate the boundaries of the table and cells.

    
    
        Table with auto-width sizing and overflow hiding.
        
    
    
        Table with one fluid column:
        
    row 1 a whole bunch of content could go here and it still needs to fit nice into the cell without mucking things up fixie another
    Table with two fluid columns:
    row 1 a whole bunch of content could go here and it still needs to fit nice into the cell without mucking things up blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah fixie another

    I tested it in several modern browsers and seemed to work correctly in each.

    PS. Although tables are a no-no for page layout in general, tables are correct and encouraged for tabular data layout.

    0 讨论(0)
提交回复
热议问题