Search code examples
htmlcssbuttoncenter

Perfectly center button in the middle of the page


The code

<!DOCTYPE html>
<html>
<head>
<title>Google Maps</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<style type="text/css">
#button {
appearance: none;
-moz-appearance: none;
-webkit-appearance: none;
height: 30px;
width: 200px;
left: 50%;
top: 50%;
position: absolute;
}
</style>
</head>
<body>
<input type="button" id="button" value="Open Map" />
</body>
</html>

I am not sure how to properly center the button perfectly in the middle of the page. I tried using left and top 50%; but that does not perfectly center the button in the middle of the page. Thanks.

here is the demo working code attached below.

Demo code Check Out


Solution

  • You have done everything correctly, except a few changes:

    margin-top: -15px;   /* = -height / 2   */
    margin-left: -100px; /* = -width / 2    */
    position: fixed;     /* Fixed is better */
    

    Snippet

    #button {
      appearance: none;
      -moz-appearance: none;
      -webkit-appearance: none;
      height: 30px;
      width: 200px;
      left: 50%;
      top: 50%;
      margin-top: -15px;   /* = -height / 2   */
      margin-left: -100px; /* = -width / 2    */
      position: fixed;     /* Fixed is better */
    }
    <input type="button" id="button" value="Open Map" />