Home > database >  Setting margin-left on a button pushes it beyond the right side of the container
Setting margin-left on a button pushes it beyond the right side of the container

Time:10-03

Although I can work around this, I'm curious: why is it when I set a button's width to 100% and set the margin-left property, that it pushes it beyond the containing box (on the right side)? I've tried changing the display property on the button to other values, but I'm getting the same result. Example here: Screenshot showing odd button placement

<h1>Hello Vanilla!</h1>
<div id="one">
  <button>Beyond bounds</button>
  <div id="two">Stays in bounds</div>
</div>


div#one {
  background-color: blue;
  width: 200px;
  padding-top: 1rem;
  padding-bottom: 1rem;
}

div#two {
  background-color: green;
  margin-left: 2rem;
}

button {
  width: 100%;
  margin-left: 2rem;
}

CodePudding user response:

There are a few things to understand here.

  • div#one has a fixed pixel width (200px).
  • The button has a set width 100%. 100% means it inherits the full width of the parent container.
  • div#two has no defined width, which means it defaults to auto.
  • margin property creates extra space around an element.

With these things in mind, we can now get into specifics as to why this scenario occurs.

Since div#one is working with a set width, the space inside the container will be confined within that dimensional space.

div#two does not have any specific width, which means it defaults to auto.

What does that mean? It means that:

  1. width: auto; will try as hard as possible to keep an element the same width as its parent container when additional space is added from margins, padding, or borders. This is why that in your current scenario, div#two stays within bounds, because it has yet to break into an overflow case.

  2. width: 100%; will make the element as wide as the parent container. Extra spacing will be added to the element's size without regards to the parent. This is why the button exceeds its parent container with exactly 2rem.

  •  Tags:  
  • css
  • Related