Issue
I have the following examples to demo a font trying to stay in the middle of a div, using both normal text manipulation and flex display manipulation. Both seem to place the font in the middle, however, when your browser is not maximised and you try to change the width of the browser, both fonts wiggle within the div (you have to do this slowly to see the effect).
I made an animated GIF to show what I am talking about:
As the font size is fixed and the width and height of the enclosing div are also fixed, changing the width of the browser should not affect the position of the font within the enclosing div.
How do you make the font absolutely stable in the middle (has to be a font, not an image, can be SVG though if that is necessary), hence not wiggling when browser width changes?
div {
display: flex;
justify-content: center;
margin: 10px;
}
span.text {
height: 30px;
width: 30px;
line-height: 30px;
text-align: center;
font-size: 30px;
font-weight: bold;
color: white;
background: green;
}
span.flex {
height: 30px;
width: 30px;
display: flex;
align-items: center;
justify-content: center;
font-size: 30px;
font-weight: bold;
color: white;
background: green;
}
<div>
<span class="text">+</span>
</div>
<div>
<span class="flex">+</span>
</div>
Solution
This is subpixel rendering issue of the font. By creating a transformation layer we can somehow fix this jitter. Try backface-visibility: hidden;
for span elements
span.text {
backface-visibility: hidden;
}
span.flex {
backface-visibility: hidden;
}
Rationale
Lets assume a viewport of 1000px width. The center point is 500px. If the viewport width is 1001px, the center point is 500.5px
This decimal pixel value is called subpixel. Browsers render elements in subpixel values. But, it doesn't render fonts in subpixel.
So, the center point of the font char(+) is 500px in both 1000px & 1001px viewport cases. Whereas, for the center point of green box is 500px & 500.5px.
To fix this, we can create a layer for the green box. Consider layers as cached area that doesn't re-render unless necessary. By applying transform to an element you can paint it in a layer. Here, I used backface-visibility: hidden;
which is a property related to transformation. You can also use transform property which yields similar result.
Now, when you resize the viewport the font inside green area doesn't re-render. So, you don't see jitters
You can read https://dassur.ma/things/forcing-layers/ this article for more clarity.
Answered By - Moorthy G Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.