Home >Web Front-end >CSS Tutorial >How to Properly Set tbody Height with Overflow Scrolling in HTML Tables?
Setting tbody Height with Overflow Scroll
When working with tables in HTML, it's sometimes necessary to restrict the height of the tbody element while enabling overflow scrolling. Unfortunately, using the display: scroll property on tbody alone is insufficient.
To achieve the desired effect, a combination of CSS properties is required:
1. Block Display:
Set display: block on the tbody to break it out of the table flow and allow it to take up its own width and height.
2. Fixed Height:
Specify height: 50px (or as desired) on the tbody to define its height.
3. Table Display for Table Rows:
Set display: table on the table body's tr elements to retain their table-like behavior.
4. Fixed Table Layout:
Use table-layout: fixed on the thead and tbody tr to ensure even cell distribution.
5. Adjust thead Width:
To compensate for the scrollbar width, slightly reduce the width of the thead using width: calc(100% - 1em).
Example:
table, tr td { border: 1px solid red; } tbody { display: block; height: 50px; overflow: auto; } thead, tbody tr { display: table; width: 100%; table-layout: fixed; } thead { width: calc(100% - 1em); } table { width: 400px; }
Note:
Initially, the scrollbar may not appear if the tbody content is shorter than the specified height. To ensure a scrollbar anytime, set overflow-y: scroll on the tbody.
Additionally, it's important to consider the limitations of this approach compared to other options like grid layout or JavaScript-based solutions.
The above is the detailed content of How to Properly Set tbody Height with Overflow Scrolling in HTML Tables?. For more information, please follow other related articles on the PHP Chinese website!