【问题标题】:Perfectly center button in the middle of the page页面中间的完美居中按钮
【发布时间】:2015-11-12 08:46:01
【问题描述】:

代码

<!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>

我不确定如何正确地将按钮完全居中在页面中间。我尝试使用 left 和 top 50%;但这并不能完美地将按钮置于页面中间。谢谢。

这是下面附加的演示工作代码。

Demo code Check Out

【问题讨论】:

    标签: html css button center


    【解决方案1】:

    除了一些更改之外,您所做的一切都是正确的:

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

    片段

    #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 */
    }
    &lt;input type="button" id="button" value="Open Map" /&gt;

    【讨论】:

    • 您可以从样式中删除position: absolute
    【解决方案2】:

    给按钮一个margin-left:-width-of-the-button/2。 在你的情况下:

    margin-left:-100px;
    margin-top:-15px;
    

    【讨论】:

      【解决方案3】:

      如果按钮是正文中唯一设置为居中的元素。然后将输入字段添加到 div/span 中。然后在 cssspan/div { text-align:center; } #button { position:absolute; top:50%; } 下方应用。

      如果整个身体需要在中心,那么body { text-align:center; }

      【讨论】:

        【解决方案4】:

        您可以使用一个容器来使其更易于操作。

        这就是我所做的:

        #button {
            appearance: none;
            -moz-appearance: none;
            -webkit-appearance: none;
            height: 30px;
            width: 200px;
        
            position: relative;
            top: 50%;
            -webkit-transform: translateY(-50%);
            -ms-transform: translateY(-50%);
            transform: translateY(-50%);
        }
        .container {
            width:100%;
            height:100%;
            background-color:yellow;
            position:absolute;
            text-align:center;
        }
        

        Here is the JSFiddle demo

        【讨论】:

          猜你喜欢
          • 2013-11-15
          • 2021-09-30
          • 1970-01-01
          • 2016-04-05
          • 2023-03-27
          • 2015-04-08
          • 2017-09-05
          • 1970-01-01
          • 2015-04-02
          相关资源
          最近更新 更多