Explain Codes LogoExplain Codes Logo

How to remove word wrap from a textarea?

html
responsive-design
css
javascript
Nikita BarsukovbyNikita Barsukov·Nov 2, 2024
TLDR

To deactivate word wrap in a textarea, use the CSS property: white-space: nowrap;. Integrate this style into your textarea to keep the text in a single line and uncloak a scrollbar when exceeding the textarea width:

<textarea style="white-space: nowrap; overflow-x: auto;"></textarea>

The property overflow-x: auto; will summon a horizontal scrollbar when the text length breaches the textarea's width.

Tackling Inheritance and Edge Cases

While the suggested quick fix works for most scenarios, there exist specific cases where further tweaking might be necessary.

Overthrowing Parent Styles

Avoid falling victim to parent CSS settings causing your text to wrap unintentionally. The following CSS rule will do the trick:

/* I am my own parent! */ textarea { overflow-wrap: normal; }

Preserving Whitespace for Code

Present code or indented text faithfully by using:

/* Preserve the sanctity of whitespace! */ textarea { white-space: pre; }

Using HTML 'wrap' Attribute

Utilize the wrap="soft" attribute to instruct the browser to skip hard line wraps during text submission:

/* Now you see it! Now you don't! */ <textarea wrap="soft"></textarea>

Suppressing Vertical Scroll

Banish unnecessary vertical scrollbar with the magic spell:

/* See ya, vertical bar! */ textarea { overflow-y: hidden; }

Championing Cross-Browser Compatibility

In the wild, you deter all sorts of browser-specific quirks & foibles. Here are some tactics to take control:

Custom Horizontal Scrollbars in Firefox

Embrace -moz-scrollbars-horizontal to tame horizontal scrolling in Firefox:

/* A scroll to remember */ textarea { overflow: scroll; -moz-scrollbars-horizontal; }

Catering to Internet Explorer 11

In IE 11, use the wrap="off" attribute. It acts as 'Do not disturb' sign for word wrap. Validate that there's no offside interference from Compatibility View settings:

XHTML 1.1 Strict Accommodation

Leverage JavaScript to toggle the wrap attribute if XHTML 1.1 Strict compliance is your game:

/* XHTML Strict, meet your friend - JavaScript */ document.querySelector('textarea').setAttribute('wrap', 'off');

Spotting Outdated Information

As a responsible traveler, cross-verify your train schedules (HTML5 specs). Old printed schedules (old documentation), such as some pages on SELFHTML, might be outdated.

Testing Lanes

Map your journey across platforms to ensure compatibility. Different train lines (browsers) have their peculiarities. You want smooth rides both on Chrome Express and Firefox Local.