Explain Codes LogoExplain Codes Logo

Vertical (rotated) text in HTML table

html
responsive-design
css
accessibility
Nikita BarsukovbyNikita Barsukov·Dec 5, 2024
TLDR

Use CSS transform: rotate(-90deg); on a div within your table cell to vertically display text.

<td><div style="transform: rotate(-90deg); white-space: nowrap;">Vertical</div></td>

The transform: rotate(-90deg); rotates your text 90 degrees left, ideal when you have slender table headers needing a little twist. white-space: nowrap; keeps your text from wrapping, ensuring crisp, clean vertical lines.

For cross-browser compatibility, remember the -webkit-transform and -ms-transform tags:

.box_rotate { -webkit-transform: rotate(-90deg); /* Somersaults for Safari */ -ms-transform: rotate(-90deg); /* Cartwheels for IE 9 */ transform: rotate(-90deg); /* Pirouettes for the rest */ }

To rotate like a text gymnast, apply the .box_rotate class to your div:

<td> <div class="box_rotate">Vertical</div> </td>

Always test your text pirouetting across different browsers and devices and modify for long headings to fit with the page layout.

Applying rotation to header text

Use the same .box_rotate class to vertically rotate your header text to solve table layout challenges.

<th> <div class="box_rotate" aria-label="Vertical Header Text"> Header Text </div> </th>

Handling extended content

When words start to go the distance:

  • Abbreviate content: Words are like cake, sometimes a slice is enough.
  • Font-size alteration: Like your favourite band, fonts sometimes need to go small.
  • Change the angle: Adjust to -45deg or -60deg; you're the Picasso of your table design.

Accessibility focus

Disability is a matter of perception. Structure your HTML to be understandable for assistive technologies and screen readers.

<th> <div class="box_rotate" aria-label="Helpful description for screen reader users"> Unhelpfully short abbreviation </div> </th>

This design not only looks good but also communicates well.

Designing for mobile users

Think small for big usability.

  • Media Queries: hear the call and answer with rotate only on larger screens.
  • Flexible, not fixed, sizing: build for gadgets both big and small with adjustable sizes.
@media (min-width: 768px) { .box_rotate { transform: rotate(-90deg); /* When size matters, we rotate */ } }

Anticipating potential pitfalls and solutions

Consider this section your CSS stunt double.

  • Alignment: CSS acting up? Use text-align and vertical-align to straighten it out.
  • Overlap: If rotated text overlaps, make your table layout more flexible or loosen the font waistband with a smaller font-size.
  • Hover: Be wary of hover styling quirks that can cause visual confusion when text is rotated.

Test the waters before taking the plunge to ensure a happy balance of form and function.