Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

button with display:block not stretched

Tags:

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.

like image 577
Martin Ždila Avatar asked Mar 14 '12 09:03

Martin Ždila


2 Answers

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/

like image 56
welldan97 Avatar answered Sep 27 '22 17:09

welldan97


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

like image 35
彼術向 Avatar answered Sep 27 '22 16:09

彼術向