Make the button fill the full width of the container element?

I am using div

both buttons for actual buttons and now I need the buttons to 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>
      

Run codeHide result


Adding display:block

in .button

doesn't work (although I'm sure I should be part of the answer?) And doesn't matter left: 0; right: 0

. width: 100%

but it ignores the container's fill property and makes the button too close to the right side of the container.

Here is a JSFiddle: http://jsfiddle.net/mn40mz2n/

+3


source to share


4 answers


Add property "box-sizing: border-box" to all elements. The width and height properties include padding and border, but not margin. This will ensure that item measurements are correct and that the shim is taken into account. display: block and width: 100% is the correct way to traverse the full width, but you need to remove the left / right margin on the button as it pushes it outside of 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 window sizing property, read the MDN docs .

+2


source


Possible answers:

Answer 1: Why display: block non-stretch buttons or input elements

Answer 2: CSS positioning to fill container: width against left / right?



width: 100%

      

works correctly. The button moves to the right because of the button left-margin

in the button.

+4


source


You can use CSS3 calc () .

If you need this to work with 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>
      

Run codeHide result


+2


source


It shouldn't be too difficult. Flip it up to what you want in the first place and then add padding, etc. For your button, just do this and it will stretch to its full width.

.button {
    width:100%;
    display:block;
}

      

+1


source







All Articles