【问题标题】:Make a button fill the full width of container element?使按钮填充容器元素的整个宽度?
【发布时间】:2015-05-31 13:47:53
【问题描述】:

我正在从将 div 用作按钮转换为实际按钮,现在我需要让按钮填满容器的整个宽度。

代码:

.container {
  background-color: #ddd;
  padding: 10px;
  max-width: 500px;
  margin-left: auto;
  margin-right: auto;
}

.button {
  display: block;
  background-color: #bbb;
  margin: 10px;
  padding: 10px
}
<div class="container">

  <div class="button">
    Fills the full width
  </div>

  <button class="button">
    Does not fill the full width
  </button>

</div>

display:block 添加到.button 不起作用(尽管我确定这一定是答案的一部分?),left: 0; right: 0 也不起作用。 width: 100% 有点工作,但它忽略了容器的填充属性并使按钮离容器的右侧太近。

这里是 JSFiddle:http://jsfiddle.net/mn40mz2n/

【问题讨论】:

    标签: css


    【解决方案1】:

    为所有元素添加“box-sizing:border-box”属性。宽度和高度属性包括填充和边框,但不包括边距。这将确保您跨元素的测量是正确的,并考虑到填充。 display: block and width: 100% 是全宽的正确方法,但您需要删除按钮上的左/右边距,因为它将按钮推到包含元素之外。

    * {
        box-sizing: border-box
    } 
    
    .container {
        background-color: #ddd;
        padding: 10px;
        margin: 0 auto;
        max-width: 500px;
    }
    
    .button {
        background-color: #bbb;
        display: block;
        margin: 10px 0;
        padding: 10px;
        width: 100%;
    }
    

    有关 box-sizing 属性的更多信息,请阅读 MDN docs

    【讨论】:

    • 这解决了我在 Anki 上长期使用不同卡组的问题。
    【解决方案2】:

    不需要太复杂。首先将其归结为您希望它执行的操作,然后再添加填充等。对于您的按钮,只需执行此操作,它将拉伸到整个宽度。

    .button {
        width:100%;
        display:block;
    }
    

    【讨论】:

      【解决方案3】:

      可能的答案:

      Answer 1: Why does display:block not stretch buttons or input elements

      Answer 2: CSS positioning to fill container: width vs. left/right?

      width: 100%
      

      工作正常。由于按钮中的left-margin,按钮向右移动。

      【讨论】:

        【解决方案4】:

        您可以使用CSS3 calc()

        如果您需要它在旧版浏览器上工作,请参阅接受here

        .container {
          background-color: #ddd;
          padding: 10px;
          max-width: 500px;
          margin-left: auto;
          margin-right: auto;
        }
        
        .button {
          display: block;
          background-color: #bbb;
          margin: 10px;
          padding: 10px
        }
        
        button.button {
          width: calc(100% - 20px);
        }
        <div class="container">
        
          <div class="button">
            Fills the full width
          </div>
        
          <button class="button">
            Does not fill the full width
          </button>
        
        </div>

        【讨论】:

        • 这对我来说太棒了,而且很新鲜。很确定box-sizing: border-box 更符合我的想法,但也许这是一个更好的方法?当然,不受支持的浏览器不是问题。
        • 是的,CSS3 calc() 很棒。我想更改您原始标记的最小值,但值得一提的是,我会尝试使用@JoshuaKelly 的方法,因为它更简单并且“越简单越好”。
        猜你喜欢
        • 1970-01-01
        • 2018-04-29
        • 1970-01-01
        • 1970-01-01
        • 2016-06-01
        • 2017-01-13
        • 2011-01-15
        • 2020-02-03
        • 1970-01-01
        相关资源
        最近更新 更多