Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a button fill the full width of container element?

Tags:

css

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.

enter image description here

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/

like image 301
Alesh Houdek Avatar asked May 31 '15 13:05

Alesh Houdek


People also ask

How do you make a button full width of a container?

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.


1 Answers

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.

like image 158
Joshua Kelly Avatar answered Sep 23 '22 05:09

Joshua Kelly