Search code examples
cssbuttoncentering

CSS code to horizontally center a 2-line button


Newbie here. I've been trying and I can't seem to figure this one out. I have a good looking 2-line button that works well. I want to horizontally center it on the page but I can only figure out how to make it go left or right.

HTML:
<a href="#" target="_blank" class="button">abcd efgh ijk lmn opqrstu<br>(abcd efrghijk + lmno pqurstuvwk)</a>

CSS:
.button {
  width: 250px;
  float: left;
  text-align: center;
  border-top: 1px solid #96d1f8;
  background: #65a9d7;
  background: -webkit-gradient(linear, left top, left bottom, from(#3e779d), to(#65a9d7));
  background: -webkit-linear-gradient(top, #3e779d, #65a9d7);
  background: -moz-linear-gradient(top, #3e779d, #65a9d7);
  background: -ms-linear-gradient(top, #3e779d, #65a9d7);
  background: -o-linear-gradient(top, #3e779d, #65a9d7);
  padding: 9.5px 19px;
  -webkit-border-radius: 13px;
  -moz-border-radius: 13px;
  border-radius: 13px;
  -webkit-box-shadow: rgba(0, 0, 0, 1) 0 1px 0;
  -moz-box-shadow: rgba(0, 0, 0, 1) 0 1px 0;
  box-shadow: rgba(0, 0, 0, 1) 0 1px 0;
  text-shadow: rgba(0, 0, 0, .4) 0 1px 0;
  color: white;
  font-size: 16px;
  font-family: Georgia, serif;
  text-decoration: none;
  vertical-align: middle;
}

.button:hover {
  border-top-color: #28597a;
  background: #28597a;
  color: #ccc;
}

.button:active {
  border-top-color: #1b435e;
  background: #1b435e;
}

Solution

  • Flexbox solution: Wrap the button within a container and use flexbox. Remove the float from the button.

    .container {
      display: flex;
      justify-content: center;
    }
    .button {
      width: 250px;
      text-align: center;
      border-top: 1px solid #96d1f8;
      background: #65a9d7;
      background: -webkit-gradient(linear, left top, left bottom, from(#3e779d), to(#65a9d7));
      background: -webkit-linear-gradient(top, #3e779d, #65a9d7);
      background: -moz-linear-gradient(top, #3e779d, #65a9d7);
      background: -ms-linear-gradient(top, #3e779d, #65a9d7);
      background: -o-linear-gradient(top, #3e779d, #65a9d7);
      padding: 9.5px 19px;
      -webkit-border-radius: 13px;
      -moz-border-radius: 13px;
      border-radius: 13px;
      -webkit-box-shadow: rgba(0, 0, 0, 1) 0 1px 0;
      -moz-box-shadow: rgba(0, 0, 0, 1) 0 1px 0;
      box-shadow: rgba(0, 0, 0, 1) 0 1px 0;
      text-shadow: rgba(0, 0, 0, .4) 0 1px 0;
      color: white;
      font-size: 16px;
      font-family: Georgia, serif;
      text-decoration: none;
      vertical-align: middle;
    }
    .button:hover {
      border-top-color: #28597a;
      background: #28597a;
      color: #ccc;
    }
    .button:active {
      border-top-color: #1b435e;
      background: #1b435e;
    }
    <div class="container">
      <a href="#" target="_blank" class="button">abcd efgh ijk lmn opqrstu<br>(abcd efrghijk + lmno pqurstuvwk)</a>
    </div>