Explain Codes LogoExplain Codes Logo

How to wrap text of HTML button with fixed width?

html
text-wrapping
responsive-design
css-properties
Anton ShumikhinbyAnton Shumikhin·Aug 9, 2024
TLDR

To ensure text wraps within a fixed-width button, apply the CSS properties white-space: normal; and word-wrap: break-word;:

<button style="width: 100px; white-space: normal; word-wrap: break-word;"> Long Text That Must Wrap Into Button Not Outside </button>

This results in a button with a fixed width of 100px and the text wraps as needed.

Going deeper: HTML and CSS strategies for wrapping text

Achieving the desired text wrapping requires attention to various aspects like HTML structure, CSS rules, browser compatibility & usability. Here's a quick dive into these aspects:

Using span for finer text control

A <span> element inside your button can provide extensive control over your button's text layout and wrapping:

<button style="width: 100px;"> <span style="white-space: normal; display: inline-block;"> Now I Control My Text, Not The Text Controls Me </span> </button>

Tip: It's like putting a belt on your overflowing pants (text), and suddenly everything feels under control!

Provide multiline support for iOS

If your userbase includes legacy iOS users, ensure multiline text support with height: 100%;:

button { /* Making multiline text great again, even on iOS */ height: 100%; overflow: hidden; }

Leveraging alternate HTML elements for wrapping

Sometimes, text wrapping is about thinking outside of the box, or in this case, the button:

<div role="button" style="width: 100px; white-space: normal; word-wrap: break-word;"> I'm Not A Button, But I Can Act Like One </div>

Remember to always check your solution on various browsers.

Polishing your button: design considerations and techniques

When wrapping button text, we aim for optimal visibility and functionality without compromising the button’s design. Here are four tactics to achieve this:

Trimming

Eliminate unnecessary text for better readability. A button isn't a novel, the less text, the better.

Ditching <br> tags

Allow CSS to handle text wrapping, keeping your HTML clean. Remember, <br> tags in buttons is like pineapple on pizza, some might not agree!

Integrating CSS properties

Take advantage of CSS properties, like height: 100%;, to avoid cape-crusader-text (text that likes to hang outside the button).

Responsive design

Consider fixed vs flexible design elements to ensure text visibility and button aesthetics. Sometimes less rigidity means more adaptability.