【问题标题】:What is the proper way to center this button? [duplicate]使此按钮居中的正确方法是什么? [复制]
【发布时间】:2018-05-10 09:25:09
【问题描述】:

我的页面上有这个按钮,该按钮当前与屏幕左侧对齐,但我希望它位于中间。实现这一目标的正确方法是什么?

html

<button class="button">Button</button>

css

.button {
    background-color: #4CAF50; /* Green */
    border: none;

    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
}

【问题讨论】:

  • 对他的父母使用text-align:center; display: inline-block。您应该为您的问题分享所有相关代码
  • 去掉填充...并设置对齐:居中。

标签: html css


【解决方案1】:

添加一个带有text-align: center; 和position 的wrapper 按钮将其置于中心:

.wrapper {
  text-align: center;
}

.button {
  position: absolute;
  top: 50%;
  background-color: #4CAF50;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
}
<div class="wrapper">
  <button class="button">Button</button>
</div>

【讨论】:

  • 这不是居中的!它在最右边。 position: absolute; 制动水平居中 (jsfiddle.net/p1ztx2ga) 如果您将其移除 (jsfiddle.net/p1ztx2ga/1),那么它至少水平居中。简而言之,position:absolute; 不能很好地与 text-align: center; 配合使用
【解决方案2】:

你必须把按钮放在div中

<div style="width:100%; text-align:center;">
  <button class="button">Button</button>
<div>

您可以在这里查看Demo

【讨论】:

    【解决方案3】:

    现在应该使用 CSS3。这样,元素(按钮)的大小也无关紧要。

    .button {
        /* THE MAGIC */
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
    
        /* YOUR STYLINGS FROM QUESTION */
        background-color: #4CAF50; /* Green */
        border: none;
        color: white;
        padding: 15px 32px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
    }
    &lt;button class="button"&gt;Button&lt;/button&gt;

    如果你想水平和垂直居中它几乎是一样的

    .button {
        /* THE MAGIC */
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
    
        /* YOUR STYLINGS FROM QUESTION */
        background-color: #4CAF50; /* Green */
        border: none;
        color: white;
        padding: 15px 32px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
    }
    &lt;button class="button"&gt;Button&lt;/button&gt;

    【讨论】:

    • 不要误会我的意思,但它太大且令人困惑,无法记住所有这些......只是为了简单的问题......中心居中按钮
    • @PranayRana 仅此而已:position: absolute; left: 50%; transform: translateX(-50%); 并没有那么多。
    • 好的,我对其他属性感到困惑
    • @PranayRana 我明白了,我应该将相关更改放在顶部以使其更清楚。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-07-25
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    相关资源
    最近更新 更多