1

I want to have a border around multiple divs, so I was trying to set the border around the parent div. However, this leads to a slight gap between the children and the parent (One of the children will have a different background color). Is there a way to prevent this behavior?

https://jsfiddle.net/fpcg2x07/8/

.container {
  display: inline-flex;
  border: 1px solid black;
}

.child {
  padding: 0.5rem;
}

.child:first-child {
  background-color: red;
}
<div class="container">
  <div class="child">
    child1
  </div>
  <div class="child">
    child2
  </div>
</div>

Thanks!

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
Niclas do
  • 31
  • 2

1 Answers1

1

The reason is still to be figured out. Maybe this happens because of the 0.5rem padding that for some reason doesn't coincide well with the fact that zoom of browser is different than 100%. That's why px unit is better(?) Should I use px or rem value units in my CSS?)

But here's a workaround (using borders for the child indeed, but only top and bottom).

.container {
  display: inline-flex;
  border-left: 1px solid black;
  border-right: 1px solid black;
}

.child {
  padding: 0.5rem;
  border-top: 1px solid black;
  border-bottom: 1px solid black;
}

.child:first-child {
  background-color: red;
}
<div class="container">
  <div class="child">
    child1
  </div>
  <div class="child">
    child2
  </div>
</div>
IT goldman
  • 14,885
  • 2
  • 14
  • 28
  • Thanks, thats what my workaround was as well. It's kind of counterintuitive though. Does anyone know why the gap exists between the parent and the children? – Niclas do Jul 10 '22 at 10:39
  • I think you are seeing an edge effect when the browser has to decide how to map a part CSS pixel to screen pixels. There may be several screen pixels to one CSS pixel on modern screens. Sometimes a screen pixel gets ‘left behind’, sort of like a rounding error. – A Haworth Jul 10 '22 at 14:39