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/
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. for more information on the box-sizing property, read the MDN docs.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With