Home > Enterprise >  child button exceeds parent absolute container
child button exceeds parent absolute container

Time:06-19

I am trying to make a list of buttons in an absolute <div>. The buttons should span over the whole <div> container, without exceeding them. They do though I am wondering what I did wrong.

.container {
  position: absolute;
  background-color: yellow;
 }
 
 .btn {
  padding: 8px;
  margin: 8px;
  width: 100%;
  display: block;
  background-color: blue;
 }
<div >
  <button >Text</button>
  <button >Text2</button>
 </div>

CodePudding user response:

Since you are using margin in your child element, the container will have the width of child only. But when using margin, it will overflow the element.

One way to workaround is to give a padding on left and right on the container, and a margin top and bottom on the child. Hope it makes sense.

.container {
  position: absolute;
  background-color: yellow;
  padding: 0 8px;
 }
 
 .btn {
  padding: 8px;
  margin: 8px 0;
  width: 100%;
  display: block;
  background-color: blue;
 }
<div >
  <button >Text</button>
  <button >Text2</button>
 </div>

Regards

CodePudding user response:

Margins that are hardcoded to a value will take precedence over relative sizing. As a result, it will push make space for the element on the DOM irrespective of the properties of its parent container.

A way to achieve what you want is to set the padding (to the same size as your required margin) on the parent container instead as I've done to achieve the border gap you're looking for rather than setting margin on the buttons themselves.

.container {
  position: absolute;
  background-color: yellow;
  padding: 8px;
 }
 
 .btn {
  padding: 8px;
  width: 100%;
  display: block;
  background-color: blue;
 }
<div >
  <button >Text</button>
  <button >Text2</button>
 </div>

  • Related