Warm tip: This article is reproduced from stackoverflow.com, please click
css html

button with display:block not stretched

发布于 2020-03-28 23:13:27

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.

Questioner
Martin Ždila
Viewed
18
welldan97 2012-03-14 17:35

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/