Last updated: Apr 5, 2024
Reading time·3 min
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">bobbyhadz.com</div> <br /> <br /> <button class="btn">Click Example</button> </body> </html>
And here is the related style.css
file.
.btn { 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; }
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; }
In general, you shouldn't set a fixed width
on button elements. Instead, you
should use padding.
.btn { width: auto; padding: 5px 50px; }
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
:
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%; }
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.
You can learn more about the related topics by checking out the following tutorials: