CSS pseudo-element & Top property for Firefox only?

I’m simulating a line-through in order to decorate some text.

<span>Some Text</span>

and the css:

span {
  box-sizing: border-box;
  text-decoration: none;
  position: relative;
}

span::before {
  content: '';
  width: 110%;
  position: absolute;
  right: 5%;
  left: -5%;
  top: calc(50% - 0.25px);
  border-bottom: 1px solid rgba(255, 0, 0, 0.8);
}

Works just fine, but for firefox I need the top property to be something like: top: calc(50% - 0.5px);

I tried, but no success with:

@supports (-moz-appearance: none) {
  note::before {
    top: calc(50% - 0.5px) !important;
  }
}

Any ideas how I could accomplish it?

Hi,

There is no such thing as pixel fractions, the browser will always try to make it the rounded pixel, so it will either be -0px or -1px. The rounding can vary between browsers.

I suggest you to accept the odd pixel off in the line-through position.
Or you could decide the line height in pixel to get the correct position.

Otherwise you could try using another unit, like e.g. em instead of px, that refer to the font size and let the browser do the rounding to pixels when rendering.

2 Likes

Thanks man, as you said: There is no such thing as pixel fractions … sometimes we forget about these obvious things!!!

1 Like

Rather than immediately looking for a hack to fix a problem you really need to sit down and work out why there is a difference in the first place and then see if it can be solved for both browsers (or all browsers within reason) without forking the code into hacks for different browsers. (We went down the road with IE6 and some of us never returned :slight_smile: )

In some cases it may indeed be a bug and you have no choice but to use a hack or just live with the odd pixel.

In the case of your line-through if you control everything (line-height, font-size and family) and use values that make sense then you are more likely to get the result you want.

In the following example the line-through is exactly the same in both browsers as seen in the screenshot that follows.

Screen Shot 2021-05-30 at 12.42.41

The above is a screenshot of Chrome and Firefox side by side using the code from the codepen.

As Erik said above browsers will round up and down differently and indeed some will remember half pixels and try to compensate so there is never any real guarantee of pixel perfection but generally if you control things explicitly you can minimise the issues.

3 Likes

Once I replaced the font-size from pixel to rem I’ve got a similar result as yours and solved the line-through issue without even having to rely on browser specific code like before. But it’s always nice to see different implementations.

2 Likes

<post script>

It’s worth remembering that the user can change the font and font-size to suit himself (his needs), so “guaranteed” precision may be impossible to achieve.smile

2 Likes