Home > Enterprise >  Fractional border width sometimes causes a 1px "padding", how to fix?
Fractional border width sometimes causes a 1px "padding", how to fix?

Time:03-11

To create a rounded rectangle with a 3D-like effect, I have a div inside a div, as follows:

* {
  box-sizing: border-box;
}

.outer {
  font-size: inherit;
  width: 20em;
  height: 26em;
  background: #f6c;
  border: 1.4em solid #bad9d9;
  border-radius: 3.98em;
  line-height: 20.8em;
  text-align: center;
}
.inner {
  font-size: 8.64em;
  height: 87%;
  background: #fff;
  border-radius: 2.844px;
}
<div >
  <div >768</div>
</div>

In this code, I am trying to create this, but depending on the exact value of div.outer's font-size (set via JavaScript), a 1-pixel padding sometimes develops at the top and/or sides of the outer rectangle, as shown here. I believe this is caused by the browser rounding the fractional border width up for positioning elements, but rounding it down when drawing it on the screen. This effect (bug?) occurs in Chrome and Edge, but not Firefox.

Edit: I would like to clarify that almost all the styles are dynamically updated via JavaScript (this is part of a larger project). The border-width could shrink to 0em or expand to 4em, and I am looking for a workaround to this bug (I believe it is a rendering bug) that works for any border-width.

My question: is there a way to fix this without

  • Using JavaScript to convert from em values to rounded px values?
  • Using a third element to draw the border (pseudo- or otherwise)?

Gallery:

original - original

at 500% zoom - at 500% zoom

with the border-width at 1.0em - with the border-width at 1.0em

with the border-width at 0.8em - with the border-width at 0.8em (what I want)

with the border removed - with the border removed

(all screenshots scaled up using Chrome's trackpad pinch-zoom)

CodePudding user response:

This is a known and reported issue, but currently this is considered low priority by the Chromium development team, so there's not much hope this will be fixed any time soon, if ever.

Here's the change that causes this: Use floor instead of round for decimal border widths; here's an explainer for the change.

Adding your case and a reproducer to that issue might help.

CodePudding user response:

I would prefer not to mix different types of Units use em everywhere. In addition, make the inner width 100% so it always fills the outer and does not have extra space of the outer visible.

CodePudding user response:

I would say that .outer should have the border like :

border: 0.7em solid #bad9d9;

and the .inner should also have these stylings :

  border-radius: 50.844px;
  text-align:center;

hope that may solve your problem :D

  • Related