Reputation: 998
I'm converting from using div
's as buttons to actual buttons, and now I need to make buttons fill the full width of the container.
Code:
.container {
background-color: #ddd;
padding: 10px;
max-width: 500px;
margin-left: auto;
margin-right: auto;
}
.button {
display: block;
background-color: #bbb;
margin: 10px;
padding: 10px
}
<div class="container">
<div class="button">
Fills the full width
</div>
<button class="button">
Does not fill the full width
</button>
</div>
Adding display:block
to .button
does not work (although I'm sure that has got to be part of at the answer?), and neither does left: 0; right: 0
. width: 100%
sort of works, but it ignores the container's padding property and makes the button go too close to the right side of the container.
Here is the JSFiddle: http://jsfiddle.net/mn40mz2n/
Upvotes: 38
Views: 164622
Reputation: 4431
Possible answers:
Answer 1: Why does display:block not stretch buttons or input elements
Answer 2: CSS positioning to fill container: width vs. left/right?
width: 100%
is working properly. The button moves towards right because of the left-margin
in the button.
Upvotes: 7
Reputation: 2962
It doesn't need to be too complicated. Boil it down to what you want it to do first, and then add padding, etc afterward. For your button just do this, and it will stretch to the entire width.
.button {
width:100%;
display:block;
}
Upvotes: 23
Reputation: 1063
Add the "box-sizing: border-box" property to all elements. The width and height properties include the padding and border, but not the margin. This will ensure your measurements across elements are correct and take into account the padding. display: block and width: 100% is the correct way to go full width but you need to remove the left/right margin on the button as it pushes it outside the containing element.
* {
box-sizing: border-box
}
.container {
background-color: #ddd;
padding: 10px;
margin: 0 auto;
max-width: 500px;
}
.button {
background-color: #bbb;
display: block;
margin: 10px 0;
padding: 10px;
width: 100%;
}
for more information on the box-sizing property, read the MDN docs.
Upvotes: 40
Reputation: 5444
You can use the CSS3 calc().
If you need this to work on legacy browsers, see the acceptance here.
.container {
background-color: #ddd;
padding: 10px;
max-width: 500px;
margin-left: auto;
margin-right: auto;
}
.button {
display: block;
background-color: #bbb;
margin: 10px;
padding: 10px
}
button.button {
width: calc(100% - 20px);
}
<div class="container">
<div class="button">
Fills the full width
</div>
<button class="button">
Does not fill the full width
</button>
</div>
Upvotes: 6