Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent fractional pixels in an element with width set to auto?

Tags:

css

sass

I have a row of inline-block elements that all have auto width, so they draw as wide as the varying text content in each of them plus a bit of padding. This results in the actual width of each element having fractional pixels.

This would be fine, but each element contains an icon font that is very sensitive to being drawn when not aligned to the pixel grid, the subpixel rendering of it just looks nasty and blurry if the glyph's origin is not at an integer pixel value.

How can I keep the width of these elements dynamic while preventing decimal pixel values? For example, one of the elements ends up with the width 60.183px when I'd like it to be rounded up to 61px. Sass can do ciel(), which would be perfect, but there is seemingly no way to apply it to auto values.

Or alternatively, is there any way I can ensure that the icon glyphs have an origin that is a full integer pixel without rounding the container widths?

Because of the way these elements are used I'd like to avoid doing this with JS and find a CSS/SASS only solution.

like image 545
Kris Avatar asked Oct 04 '16 21:10

Kris


People also ask

Can you have a fraction of a pixel?

Yes, you can specify fractional pixels. As this has been part of CSS since the very first version, it should be well supported by any browser that supports CSS at all.

Can you have half pixels in CSS?

On high DPI/PPI devices, a single CSS pixel may become two physical pixels. A 4px measure may become 6px, or 8px. Fractional pixels are actually quite useful as a 0.5px border should round up to 1px at 1.0 scale factor, and remain 1px (as thin as possible) at 1.5 or 2.0 scale.


1 Answers

I have found that if you use display: inline-table; instead of display: inline-block; it will force it to render exact pixel widths/heights. This may fix your issue however using table/inline-table will make the space within container collapse in some browsers so you would have to wrap the contents in another element.

like image 147
Steve Avatar answered Oct 27 '22 15:10

Steve