-1

I have this button on my page that is currently aligned to the left side of my screen but I want it to be in the middle. What would be the proper way to achieve this?

html

<button class="button">Button</button>

css

.button {
    background-color: #4CAF50; /* Green */
    border: none;

    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
}
Lelio Faieta
  • 6,457
  • 7
  • 40
  • 74
Jordan Jones
  • 125
  • 10

3 Answers3

1

Add a wrapper with text-align: center; and position the button to place it in center:

.wrapper {
  text-align: center;
}

.button {
  position: absolute;
  top: 50%;
  background-color: #4CAF50;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
}
<div class="wrapper">
  <button class="button">Button</button>
</div>
Milan Chheda
  • 8,159
  • 3
  • 20
  • 35
  • This is not centered! It's to far to the right. The `position: absolute;` brakes the horizontal centering (https://jsfiddle.net/p1ztx2ga/) if you remove it (https://jsfiddle.net/p1ztx2ga/1/) then it's at least centered horizontally. In short `position:absolute;` does not work nicely with `text-align: center;` – caramba Nov 27 '17 at 09:56
0

you have to put button in div

<div style="width:100%; text-align:center;">
  <button class="button">Button</button>
<div>

You can check here Demo

Saurabh Solanki
  • 2,146
  • 18
  • 31
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
0

Using CSS3 these days should be the way to go. With this also the size of the element (button) does not matter.

.button {
    /* THE MAGIC */
    position: absolute;
    left: 50%;
    transform: translateX(-50%);

    /* YOUR STYLINGS FROM QUESTION */
    background-color: #4CAF50; /* Green */
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
}
<button class="button">Button</button>

If you want to center both horizontally and vertically it's almost the same

.button {
    /* THE MAGIC */
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);

    /* YOUR STYLINGS FROM QUESTION */
    background-color: #4CAF50; /* Green */
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
}
<button class="button">Button</button>
caramba
  • 21,963
  • 19
  • 86
  • 127