首页 > 解决方案 > 嘿,我怎么把这个按钮放在中间?

问题描述

[我的网站图片1

嘿,所以如果你在那里看到那张图片,那么我只想知道如何将按钮放在中心,就像标题一样。就像直接在它下面一样, text-align 对我不起作用。

请让我知道我的代码中是否有任何内容阻止按钮进入中心。(我是 HTML 新手)

我的代码:

<html style = "background-color: lightblue;">
<b
  ><h1 id="chimp">
    Welcome to Monkey Idle!
  </h1></b
>
<a class="button" href="" style="text-decoration: none; color: black" id = "button">
  Click Here to Play!
</a>
<a id="button2" class="button" href="" style="text-decoration: none; color: black;">
  Played before? Click here!
</a>
<style>
  #chimp {
    text-align: center;
    font-size: 50px;
    font-family: cursive;
  }
  #moneycount {
    border-style: solid;
  }
  #button2 {
  text-align: center;
  background color;
    position:absolute;
    left: 50%;
    font-family: cursive;
    background-color: white;
    padding: 20px;
    position: center;
    align: center;

  }
  @keyframes buttonbounce {
    0%{margin-left: 0px;}
    100%{margin-left: 10px;}
  }
  #button2:hover {
        animation: buttonbounce 0.1s infinite;
  }
  #button {
      text-align: center;
  background color;
    position:relative;
    
    font-family: cursive;
    background-color: white;
    padding: 20px;

  }
</style>
</html>

标签: htmlcssbuttoncenterhtml-helper

解决方案


text-align 不适用于按钮的原因是按钮不被视为文本。当您使用 text-align 时,您将在父元素中居中文本,而不一定是页面的中心。例如,按钮上的文本对齐只会将文本居中在按钮的中心。如果要使按钮居中,可以将按钮包装在 div 中,并使用Flexbox。如果您开始进行 Web 开发,我强烈推荐前面提到的 Flexbox 以及用于页面布局的CSS Grid 。

#button-wrapper {
  display: flex;
  justify-content: center;
}
<div id="button-wrapper">
  <button>My button!</button>
</div>


推荐阅读