5

I would like to center a button horizontally and verticaly in a middle of a div for my project.

Here is the html code:

<div class="PageHeader_wrapper" id="header-buttons">
  <form id="CreateAccount" action="CreateAccount.php" method="post">
    <input type="submit" value="Create an account">
  </form>
</div>

and the CSS here :

#header-buttons {
  margin-right: 35px;
  float: right;
  height: 68px;
  width: auto;
  border: 1px solid red;
} 

Js fiddle here: https://jsfiddle.net/m635r2rf/10/

halfer
  • 19,824
  • 17
  • 99
  • 186

5 Answers5

6

Use a combination of display: flex; align-items: center; justify-content: center;. Also, this is a useful reference https://www.w3.org/Style/Examples/007/center.en.html

#header-buttons {
  margin-right: 35px;
  float: right;
  height: 68px;
  width: auto;
  border: 1px solid red;
  display: flex;
  align-items: center;
  justify-content: center;
}
<div class="PageHeader_wrapper" id="header-buttons">
  <form id="CreateAccount" action="CreateAccount.php" method="post">
    <input type="submit" value="Create an account">
  </form>
</div>
Michael Coker
  • 52,626
  • 5
  • 64
  • 64
4

A simple solution is to use flexbox: Add these settings to your wrapper:

  display: flex;
  align-items: center;
  justify-content: center;

https://jsfiddle.net/3t7ynn6p/

Johannes
  • 64,305
  • 18
  • 73
  • 130
0

What you're looking for is to set a line-height on the form element:

#CreateAccount {
  line-height: 60px;
}

This is 60px in this situation because your parent element is 68px, and the default font-size is 16px. Half of the font-size of the button should equal the difference from the parent's line-height.

Essentially, it would be:

#CreateAccount {
  line-height: calc(100% - (1em /2)); /* calc([parent height] - ([font-size] / 2)); */
}

I've created a fiddle showcasing this here.

Hope this helps! :)

Obsidian Age
  • 41,205
  • 10
  • 48
  • 71
0

You can use table for that (probably easiest and most backward-compatible method).

#header-buttons {
    margin-right: 35px;
    float: right;
    height: 68px;
    width: auto;
    border: 1px solid red;
    display: table;
}

#CreateAccount {
    display: table-cell;
    vertical-align: middle;
}

for horizontal alignment just use text-align property (as button is inline-block) as in example here: https://jsfiddle.net/m635r2rf/64/

0

HTML code change: added one id for button to select.

 <div class="PageHeader_wrapper" id="header-buttons">
              <form id="CreateAccount" action="CreateAccount.php" method="post">
                <input type="submit" id="createBtn" value="Create an account">
      </form>

CSS code change: removed styling from div and added in the button as below -

 #createBtn {
   position: fixed;
   left: 50%;
   top:50%;
 }
MadhuriJain
  • 145
  • 2
  • 4