带显示的按钮:块未拉伸

Mar*_*ila 15 html css

请考虑以下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>
Run Code Online (Sandbox Code Playgroud)

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

彼術向*_*彼術向 9

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

我们可以参考HTML Living Standard来查看按钮布局的一条重要规则,如下所示:

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

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>
Run Code Online (Sandbox Code Playgroud)

查看结果


wel*_*n97 8

您可以向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>?
Run Code Online (Sandbox Code Playgroud)

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