-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,242
  • 6
  • 38
  • 64
Jordan Jones
  • 105
  • 9

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,009
  • 3
  • 19
  • 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,086
  • 15
  • 29
Pranay Rana
  • 170,430
  • 35
  • 234
  • 261
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,282
  • 18
  • 84
  • 125