Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent a <button> shrinking to the size of it's content?

Tags:

html

css

I have two elements in a container:

<div class="container">
    <span>This is a div</span>
    <button>This is a button</button>
</div>

Styled as follows:

span, button {
    display: block;
    padding: 4px;
    border: 1px solid black;
    margin: 5px;
    background: #c0c0c0;
    font: inherit;
}

.container {
    border: 1px solid black;
}

You can see a live demo here.

Why does the button not appear the same width as the span? How can I make the button behave like a standard block-level element?

I need to use a <button> here because its purpose is to submit the form.

like image 757
Eric Avatar asked Jul 31 '11 15:07

Eric


2 Answers

This should do the trick. Live example: http://jsfiddle.net/925qz/18/

.container {
    border: 1px solid black;
    padding: 5px;
}
span, button {
    display: block;
    padding: 4px;
    border: 1px solid black;
    background: #c0c0c0;
    font: inherit;
}
button{
    width:100%;
    margin-top: 5px;
    text-align: left;
}
like image 82
tw16 Avatar answered Oct 26 '22 23:10

tw16


I'm expecting there to be some ruleset that makes them both behave like <div>s

There isn't. The reason is that button is a "replaced element".

The clearest source I could find on this was: http://reference.sitepoint.com/css/replacedelements

A replaced element is any element whose appearance and dimensions are defined by an external resource. Examples include images (<img> tags), plugins (<object> tags), and form elements (<button>, <textarea>, <input>, and <select> tags). All other elements types can be referred to as non-replaced elements.

Replaced elements can also have visual formatting requirements imposed by the element, outside of the control of CSS; for example, the user interface controls rendered for form elements.

like image 36
thirtydot Avatar answered Oct 26 '22 23:10

thirtydot