28

Consider the following HTML code:

<!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>

My question is why buttons don't stretch to 100% width if their display is block. How to achieve this? I can't set style of buttons to width: 100% because they would overflow their parent block because of the margin.

Martin Ždila
  • 2,998
  • 3
  • 31
  • 35

4 Answers4

24

The initial defination of Button Layout was committed on 2019, which solved the rendering problem of button elements. https://github.com/whatwg/html/pull/4143.

we could refer to the HTML Living Standard to see an important rule of Button Layout as follows:

If the computed value of 'inline-size' is 'auto', then the used value is the fit-content inline size.

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

we should know that a block with inline-size:fit-content | max-content | min-content will shrink its width even if display:block.(by the way, width:fit-content | max-content | min-content does the same effect)

try this (require chrome 57+, but in FireFox 66+ we could try with 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

彼術向
  • 341
  • 2
  • 4
10

You can add padding to div container, and remove horizontal margin from buttons. Then you can apply width 100% to them:

<!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>​

Demo: http://jsfiddle.net/xwt9T/1/

welldan97
  • 3,071
  • 2
  • 24
  • 28
0

Try with this ,

<div style="width: 100px; border: 1px solid black">
    <button style="width:100%; float: left;margin-left:0px;">hello</button>
    <button>hi</button>
</div>
rejo
  • 3,352
  • 5
  • 27
  • 34
-3

flex-grow: 1 will produce the expected behavior.

br4nnigan
  • 646
  • 6
  • 13
  • @SephReed I cannot reproduce OPs behavior now, button always stretches for me (Firefox, Chrome, IE11). What's your setup? – br4nnigan Jul 24 '19 at 08:42
  • Brave, so same thing. Inversely related: https://stackoverflow.com/questions/57154038/can-i-make-a-div-shrink-to-text-width-like-a-button – Seph Reed Jul 24 '19 at 18:48