Search code examples
cssbuttonwidthlimit

Limit Width Of The Buttons In CSS


CSS:

.btn { 
background: #53A2FF;
border: 2px solid transparent;
color: #eee;
font-weight: bold;
padding: 9px 15px;
outline: none;
transition: 0.5s all;
-webkit-transition: 0.5s all;
-moz-transition: 0.5s all;
-o-transition: 0.5s all;
-ms-transition: 0.5s all;
}
.btn:hover { 
border: 2px solid #000;
background: transparent;
color: #000;
}   

HTML:

<button class="btn">Hello Over There!</button>
<br><br>
<button class="btn">This Button Has Too Much Text, That's Why It Is Bigger!</button>
<br><br>
<button class="btn">Hello Over There! This Is The Third Button!</button>

Output will be similar to:

Buttons With Different Sizes

Size of each button depends on the amount of letters.

If I change the HTML & do something like this.

<input class="btn" value="Hello Over There!">
<br><br>
<input class="btn" value="This Button Has Too Much Text, That's Why It Is Bigger!">
<br><br>
<input class="btn" value="Hello Over There! This Is The Third Button!">

So the output will be similar to:

Buttons With Same Sizes

Size of each button will be the same. But input tag is mainly used for HTML forms and using them for making links is not a good idea at all!

I tried to do this using CSS max-width:, but the text inside the button started overflowing.

If I want to use the button tag instead of the input tag, and if I want to limit the width of buttons, so which CSS code should I use?

I exactly want the same output of input tag while using the button tag.


Solution

  • You're on the right track with max-width, but you also need to 1) make sure the text doesn't wrap, using white-space, and 2) hide the extraneous characters with overflow.

    .btn {
      background: #53A2FF;
      border: 2px solid transparent;
      color: #eee;
      font-weight: bold;
      padding: 9px 15px;
      outline: none;
      transition: 0.5s all;
      -webkit-transition: 0.5s all;
      -moz-transition: 0.5s all;
      -o-transition: 0.5s all;
      -ms-transition: 0.5s all;
      /* so these are new: */
      max-width:20em;
      white-space:nowrap;
      overflow:hidden;
    }
    
    .btn:hover {
      border: 2px solid #000;
      background: transparent;
      color: #000;
    }
    <button class="btn">Hello Over There!</button>
    <br><br>
    <button class="btn">This Button Has Too Much Text, That's Why It Is Bigger!</button>
    <br><br>
    <button class="btn">Hello Over There! This Is The Third Button!</button>