How can we rotate specific columns in a table using CSS and JavaScript?
Rotating columns in a table can be a challenge, especially when you want to only move specific columns. Usually, in web design, the control of elements should be in a form that meets the needs of most users, where the main part of user experience is considered. Therefore, when we need to rotate columns, we must consider simple and user-friendly solutions. This can be achieved using CSS and JavaScript, and here we intend to review that.
Before anything, it is important that we correctly identify the HTML structure of the table. Columns in the table are defined with the elements th
and td
, and by accessing these elements, we can make changes to them. Suppose we want to rotate the third column of the table and display it.
For this work, we must first ensure that we have the necessary styles for the rotation. This requires having a specific CSS class for rotation. Also, this rotation should only be applied to specific columns, which means we can use a JavaScript script to carry out this action dynamically.
Below is a sample code that shows how you can implement this action using CSS and JavaScript. This code includes a simple table that allows the rotation of columns.
<table id="exampleTable">
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
<th>Header 4</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1, Cell 1</td>
<td>Row 1, Cell 2</td>
<td>Row 1, Cell 3</td>
<td>Row 1, Cell 4</td>
</tr>
<tr>
<td>Row 2, Cell 1</td>
<td>Row 2, Cell 2</td>
<td>Row 2, Cell 3</td>
<td>Row 2, Cell 4</td>
</tr>
</tbody>
</table>
<style>
.rotateColumn {
transform: rotate(90deg);
transform-origin: bottom left;
}
</style>
<script>
const table = document.getElementById('exampleTable');
const rows = Array.from(table.rows);
// Rotate the third column
rows.forEach(row => {
const cell = row.cells[2];
if (cell) {
cell.classList.toggle('rotateColumn');
}
});
</script>
Line by Line Explanation of the Code
<table id="exampleTable">
: Creates a table with a specific identifier for use in JavaScript.
<thead>
and <tbody>
: Define the head and body sections of the table.
.rotateColumn
: A class in CSS that is dedicated to rotating columns.
Array.from(table.rows)
: Converts all table rows into an array.
The method toggle()
from the class rotateColumn
can be applied to the third column in each row.