在 DIV 中居中一个按钮

新手上路,请多包涵

我在将 DIV 中的按钮居中时遇到问题。

我目前得到的结果是:

div 中的按钮

HTML 是:

 <div id="buttonDiv">
<div class="button">
<button type="submit" onClick="setSid()">Click here to Start Test</button>
</div>
</div>

CSS 包括:

 #buttonDiv {
        position: fixed;
        width:200px;
        height:200px;
        top: 50%;
        left: 50%;
        margin-top: -100px;
        margin-left: -100px;
        border-bottom-width:1px;
        border-top-width:1px;
        border-right-width:1px;
        border-left-width:1px;
        border-style:solid;
        border-color:#000000;
}

.button {
     display:table-cell;
     align-content:center;
     vertical-align:middle;
}

我相信这条路线应该适用于文本,但似乎不适用于按钮。我试过将类直接添加到按钮,但没有任何乐趣。

原文由 Dan James Palmer 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 312
2 个回答

如果将 text-align center 添加到父容器,按钮将水平居中。然后你可以使用 top:50%;变换:翻译Y(-50%); 技巧垂直居中。

HTML

 <div id="buttonDiv">
<button type="submit" onClick="setSid()">Click here to Start Test</button>
</div>

CSS

 #buttonDiv {
        position: fixed;
        width:200px;
        height:200px;
        top: 50%;
        left: 50%;
        margin-top: -100px;
        margin-left: -100px;
        border-bottom-width:1px;
        border-top-width:1px;
        border-right-width:1px;
        border-left-width:1px;
        border-style:solid;
        border-color:#000000;
        text-align:center;
}

button {
   position:relative;
   top: 50%;
   transform: translateY(-50%);
}

jsfiddle 选项 1

在下方编辑

如果你需要保留 ‘.button’ div,你可以移动 top:50%;变换:翻译Y(-50%); 到那个班级。

HTML

 <div id="buttonDiv">
    <div class="button">
         <button type="submit" onClick="setSid()">Click here to Start Test</button>
    </div>
</div>

CSS

 #buttonDiv {
   position: fixed;
   width:200px;
   height:200px;
   top: 50%;
   left: 50%;
   margin: -100px 0px 0px -100px;
   border: 1px solid #000;
   text-align:center;
}
.button {
   position:relative;
   top: 50%;
   transform: translateY(-50%);
}

jsfiddle 选项 2

原文由 mattdevio 发布,翻译遵循 CC BY-SA 3.0 许可协议

尝试将盒子的 line-height 设置为它的高度;然后将按钮显示为 内联 元素并添加 text-align:center

 #buttonDiv {
        position: fixed;
        width:200px;
        height:200px;
        top: 50%;
        left: 50%;
        margin-top: -100px;
        margin-left: -100px;
        border-bottom-width:1px;
        border-top-width:1px;
        border-right-width:1px;
        border-left-width:1px;
        border-style:solid;
        border-color:#000000;
  line-height:200px;
  text-align:center;
}

.button {
     display:inline;
}
 <div id="buttonDiv">
<div class="button">
<button type="submit" onClick="setSid()">Click here to Start Test</button>
</div>
</div>

原文由 El Danielo 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题