How to adjust a Button's width to fit the Text in CSS

Borislav Hadzhiev

Last updated: Apr 26, 2023
3 min


# How to adjust a Button's width to fit the Text in CSS

To adjust a button's width to fit the text, set the width CSS property on the button to fit-content.

The fit-content CSS property makes it so the button's width will be set based on the size of its content.

Here is the HTML for the example.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="stylesheet" href="style.css" /> </head> <body> <div id="box"></div> <br /> <br /> <button class="btn">Click Example</button> </body> </html>

And here is the related style.css file.

.btn { width: fit-content; }

button width fit content

You can also set the padding CSS property to set the padding area on all four sides of the button.

.btn { width: fit-content; padding: 5px 10px; }

set padding css property

The example sets the top and bottom padding to 5px and the left and right padding to 10px.

Another thing you can try is to set the width CSS property to auto.

.btn { width: auto; padding: 5px 10px; }

When the width CSS property is set to auto, the browser calculates a width for the element.

auto is the default value for the width property.

You might run into issues if you've set the width property to a fixed value, e.g. 350px.

.btn { width: 350px; }

explicitly setting width on button

In general, you shouldn't set a fixed width on button elements. Instead, you should use padding.

.btn { width: auto; padding: 5px 50px; }

button with left and right padding

The button in the example has a top and bottom padding of 5px and left and right padding of 50px.

If the text of your button is too long and wraps to multiple lines, you can set the white-space CSS property to nowrap to prevent this behavior.

.btn { padding: 5px 10px; white-space: nowrap; }

When the white-space CSS property is set to nowrap:

  1. Sequences of whitespace are collapsed.
  2. Line breaks (text wrapping) are suppressed.

If your button's display property is set to block or inline-block, make sure its width property is not set to 100%.

Otherwise, it would use the width of its parent element.

.btn { display: inline-block; width: 100%; }

button with width set to 100 percent

If you still aren't able to set the button's width to fit its text, try setting its display property to inline-block.

.btn { display: inline-block; width: auto; }

When the display property is set to inline-block, the element generates a block element box that is flowed with surrounding content as if it were a single inline box.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.