【问题标题】:button with display:block not stretched带显示的按钮:块未拉伸
【发布时间】:2012-03-30 17:45:07
【问题描述】:

考虑以下 HTML 代码:

<!DOCTYPE html>
<html>
<head>
    <title>TEST</title>
    <style>
        button {
            display: block;
            margin: 10px;
        }
    </style>
</head>
<body>
    <div style="width: 100px; border: 1px solid black">
        <button>hello</button>
        <button>hi</button>
    </div>
</body>
</html>

我的问题是,如果按钮的 displayblock,为什么按钮不会拉伸到 100% 宽度。如何做到这一点?我无法将按钮样式设置为 width: 100%,因为它们会因为边距而溢出其父块。

【问题讨论】:

  • 你添加了 position:relative;然后添加 width:100% ?
  • Qtax: box-sizing: border-box 对我不起作用。不知道为什么。
  • EvilP: position: relative 在这里什么都不做。
  • 我知道上面只是一个例子,但你的 DOCTYPE 声明中有一个错误。

标签: html css


【解决方案1】:

您可以向div 容器添加填充,并从按钮中删除水平边距。然后你可以对它们应用宽度 100%:

<!DOCTYPE>
<html>
<head>
    <title>TEST</title>
    <style>
        button {
            display: block;
            width:100%;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <div style="width: 100px; border: 1px solid black; padding:0 10px;">
        <button>hello</button>
        <button>hi</button>
    </div>
</body>
</html>​

演示:http://jsfiddle.net/xwt9T/1/

【讨论】:

  • 我建议使用 box-sizing:border-box,将按钮填充保持在 100% 以内
【解决方案2】:

试试这个,

<div style="width: 100px; border: 1px solid black">
    <button style="width:100%; float: left;margin-left:0px;">hello</button>
    <button>hi</button>
</div>

【讨论】:

    【解决方案3】:

    flex-grow: 1 将产生预期的行为。

    【讨论】:

    • @SephReed 我现在无法重现 OP 行为,按钮总是为我伸展(Firefox、Chrome、IE11)。你的设置是什么?
    • 勇敢,同样的事情。反向相关:stackoverflow.com/questions/57154038/…
    【解决方案4】:

    ButtonLayout最初的定义是在2019年提交的,解决了按钮元素的渲染问题。 https://github.com/whatwg/html/pull/4143.

    我们可以参考HTML Living Standard看到一个重要的Button Layout规则如下:

    如果 'inline-size' 的计算值为 'auto',则使用的值为 fit-content 内联尺寸

    https://developer.mozilla.org/en-US/docs/Web/CSS/inline-size

    我们应该知道带有inline-size:fit-content | max-content | min-content 的块即使display:block 也会缩小其宽度。(顺便说一下,width:fit-content | max-content | min-content 的效果相同)

    试试这个(需要 chrome 57+,但在 FireFox 66+ 中我们可以尝试使用inline-size:max-content):

    <div style="
      inline-size: fit-content;
      background: linear-gradient(0deg, #ddd, #fff);
      padding: 2px 6px;
      border: 0.5px solid #bbb;
      font-size: 13px;"
    >click me!</div>
    

    view result

    【讨论】:

      猜你喜欢
      • 2013-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-06
      • 2021-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多