1

Working on a web app project, I came across this peculiar instance where I defined a parent element's width as a calculated value (specifically an aspect ratio to a sass variable value). The direct child's width was set to inherit, but seemed to have truncated everything after the decimal point, leaving a fraction of a pixel's difference. It seems to only occur when the child's display value is set to table-cell, which is something I'd like to keep in order to have nicely centered text supported in all browsers (as shown in this awesome dude's answer).

Other than rounding the calculated value to a whole number or explicitly setting values to "magic numbers", is there a better solution for this?

My current solution is setting the parent's width to ceil(#{$my-starting-value} * 16/9) (using Sass' ceil function) and keeping the child's width as inherit.

.parent {
  height: 100px;
  width: calc(100px * 16/9);
  
  background-color: tomato;
}

.child {
  height: inherit;
  width: inherit;
  
  text-align: center;
  vertical-align: middle;
  display: table-cell;
  
  background-color: hsl(0, 0%, 95%);
}
<div class="parent">
  <div class="child">
    My multiple-lined (and somewhat long) centered text
  </div>
</div>
Community
  • 1
  • 1
Louie Bertoncin
  • 3,744
  • 2
  • 25
  • 28
  • pixels cannot be broken into bits 177,7777777777778 wil be likely turned to 178px . 1 pixel is one dot of your screen :( – G-Cyrillus May 01 '17 at 21:12
  • I get that, but that still doesn't explain how the exact value isn't accurately passed down to the child. One element reads as `177.766px` while the other reads `177px` when they should be referencing the same value. Inspect the elements in your browser's dev tools to see, if you like. – Louie Bertoncin May 01 '17 at 21:43
  • 1
    Might be a browser issue, as it displays as 178px for both parent and child in safari 10.1 –  May 02 '17 at 01:26
  • 1
    @LouieBertoncin It's not the case that the value is inaccurately passed down to the child. In Chrome everything with `table-*` is for some reason not completely subpixel-aware. You can verify this by adding `display: table` to the parent and check the width of the parent (should be rounded now). Also keep in mind that when using `display: table-cell` the width property has no effect at all unless you set `display: table` and `table-layout: fixed` on the parent. Unfortunately, I can't cite from official sources nor can I provide a quickfix for this, so I just post my two cents as comment. – Marvin May 02 '17 at 08:12
  • @Marvin haha, yeah. That's what I hoped wasn't the case. Just another awkward edge case. Yay web development! It seems like the best solution is the `ceil` one that I'm currently going with. – Louie Bertoncin May 02 '17 at 19:59

0 Answers0