0

My child elements overflow the parent and I'm unable to understand why it's happening and how to resolve it?

<div class="parent">
  <div class="child">Child one</div>
    <div class="child">Child two</div>
</div>
.parent{
  max-width:200px;
  background:lightblue;
  margin: 3rem auto;
  padding:1rem;
    border-radius:1rem
}

.child{
  margin:1rem;
  background:lightgray;
  padding:1rem;
  border-radius:1rem;
  width:100%;
  
}

Here is a screenshot of the result: enter image description here

Here is what it should look like:

enter image description here

2 Answers2

3

It is because of width: 100%; inside .child This makes grey area be as long as the parent. On top of that you have margin of 1rem when you add that together you get overflow

Solution would be to set width to auto and let child stretch as far as it can

.child {
  margin: 1rem;
  background: lightgray;
  padding: 1rem;
  border-radius: 1rem;
  width: auto;
}

Also width is by default set to auto so you can also remove that line and get the same results. But you can keep it if you have some other rules that could override default div properties

Vojin Purić
  • 2,140
  • 7
  • 9
  • 22
0

Use flex-box


.parent{
  display: 'flex';
  justify-items: 'center';
  align-items: 'center';
  flex-direction: 'column';
  background:lightblue;
  margin: 3rem auto;
  max-width: 200px;
  padding:1rem;
  border-radius:1rem;
}

.child{
  flex-grow: 1;
  margin:1rem;
  background:lightgray;
  padding:1rem;
  border-radius:1rem;

}


isaac
  • 19
  • 5