Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to prevent text in a table cell from wrapping using CSS?
To prevent text in a table cell from wrapping using CSS, you can use the white-space property. This technique helps maintain better table layout and improves readability by ensuring text remains on a single line within cells.
Syntax
selector {
white-space: nowrap;
}
Possible Values
| Value | Description |
|---|---|
nowrap |
Prevents text from wrapping to new lines |
normal |
Default behavior - allows text wrapping |
pre |
Preserves whitespace and prevents wrapping |
Example: Preventing Text Wrapping in Table Headers
The following example demonstrates how to prevent text wrapping in table headers using the white-space: nowrap property
<!DOCTYPE html>
<html>
<head>
<style>
table {
border-collapse: collapse;
width: 60%;
}
th, td {
padding: 12px;
text-align: center;
border: 1px solid #ddd;
}
th {
background-color: #4CAF50;
color: white;
white-space: nowrap;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>City Name - First Column</th>
<th>State Name - Second Column</th>
<th>Population Count - Third Column</th>
</tr>
</thead>
<tbody>
<tr>
<td>Mumbai</td>
<td>Maharashtra</td>
<td>20.4 million</td>
</tr>
<tr>
<td>Delhi</td>
<td>Delhi</td>
<td>32.9 million</td>
</tr>
<tr>
<td>Bangalore</td>
<td>Karnataka</td>
<td>13.1 million</td>
</tr>
</tbody>
</table>
</body>
</html>
A table with green headers containing long text that remains on single lines without wrapping, even when the browser window is resized. The headers maintain their full width to accommodate the text.
Example: Applying to All Table Cells
You can also apply white-space: nowrap to all table cells
<!DOCTYPE html>
<html>
<head>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
padding: 10px;
border: 1px solid #ccc;
text-align: left;
white-space: nowrap;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<table>
<tr>
<th>Product Name</th>
<th>Description</th>
<th>Price</th>
</tr>
<tr>
<td>Wireless Bluetooth Headphones</td>
<td>High-quality audio with noise cancellation</td>
<td>$99.99</td>
</tr>
<tr>
<td>Smart Fitness Tracker</td>
<td>Monitors heart rate and daily activities</td>
<td>$149.00</td>
</tr>
</table>
</body>
</html>
A table where all text content stays on single lines without wrapping, creating a clean, uniform appearance. Long text extends the column width rather than breaking to new lines.
Conclusion
The white-space: nowrap property effectively prevents text wrapping in table cells, maintaining consistent layout and improving readability. Apply it to specific elements like headers or all table cells as needed for your design requirements.
Advertisements
