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>