簡體   English   中英

在div中水平和垂直居中按鈕

[英]Center a button horizontally and vertically in a div

我想在的中間水平verticaly 居中 按鈕 div我的項目。

這是html代碼:

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

CSS在這里:

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

Js在這里小提琴: https//jsfiddle.net/m635r2rf/10/

使用display: flex; align-items: center; justify-content: center; display: flex; align-items: center; justify-content: center; 此外,這是一個有用的參考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> 

你要找的是在表單元素上設置一個line-height

#CreateAccount {
  line-height: 60px;
}

在這種情況下,這是60px,因為您的父元素是68px,默認的字體大小是16px。 按鈕的一半字體大小應該等於父級行高的差異。

基本上,它將是:

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

我在這里創造了一個小提琴。

希望這可以幫助! :)

一個簡單的解決方案是使用flexbox:將這些設置添加到包裝器:

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

https://jsfiddle.net/3t7ynn6p/

您可以使用表(可能是最簡單和最向后兼容的方法)。

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

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

對於水平對齊,只需使用text-align屬性(如按鈕是inline-block ),如下例所示: https//jsfiddle.net/m635r2rf/64/

HTML代碼更改 :添加了一個用於選擇按鈕的ID。

 <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代碼更改:從div中刪除樣式並添加到按鈕中,如下所示 -

 #createBtn {
   position: fixed;
   left: 50%;
   top:50%;
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM