Custom WordPress site specialists - web design, hosting and online growth

Flexible padding for buttons

Buy Me a Coffee
Flexible padding for buttons

Sometimes, left and right padding on a button can cause trouble if the total width of the button does not fit inside a specific container. Making the text break to the new line makes it look bad, but letting the text overflow the button's width itself looks even worse.

That's where flexbox and pseudo-elements ::before and ::after come in handy.

Using ::before, and ::after inside a flexbox gives you the opportunity to simulate left and right padding and allowing those paddings to shrink inside of the button.

  .button {
    display: inline-flex;
    justify-content: center;
    max-width: 100%;
    line-height: 1.2;
    padding: 1.1em .75em;
    
    background-color: #004578;
    color: #ffffff;
    font-family: Arial;
    text-decoration: none;
  }
  
  .button::before,
  .button::after {
    content: '';
    display: inline-block;
    width: 2em;
    flex-basis: 2em;
    float: left;
  }

Only trouble is, without using white-space: nowrap on your button ... if a button has multiple words, then those will break into multiple lines as well as shrink the left and right paddings instead of only shrinking the left and right padding as long as the words do not need to be wrapped to the next line.

A solution we came up with for this, besides disabling word-wrapping (obviously), is wrapping the contents of the button inside of a <span> and applying both flex-shrink: 0 and max-width: 100% to it.

Option A - Prevent text shrink

  .button > span {
    flex-shrink: 0;
    max-width: 100%;
  }

Pro

  • Word-wrap is available after a button's padding is shrunk down to 0px wide

Con

  • Less consistent button HTML-markup

Option B - Prevent word-wrap

  .button {
    white-space: nowrap;
  }

Pro

  • Buttons with multiple words do not require additional HTML-markup

Con

  • Word-wrap is not available

It's up to you whether you would use white-space: nowrap on all buttons to prevent multi-word buttons from wrapping words altogether... or to wrap the content of the button inside a <span>. We recommend wrapping the content inside of a <span> (option A), thus leaving the possibility to wrap the words in case the padding is already shrunk down to 0px in width, eventhough that will make the HTML-markup for buttons a little less consistent.