Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to visually horizontally center an emoji in Chrome?

Tags:

html

css

unicode

It is surprisingly hard to visually horizontally center an emoji in Google Chrome, as there appears to be whitespace to the right of the emoji where there shouldn't be. An example:

.avatar {
  width: 30px;
  
  padding: 10px;
  background-color: #eee;
  border-radius: 50%;
  
  display: grid;
  justify-items: center;
  align-items: center;
}
<div class="avatar">
  <div>&#x1F436;</div>
</div>

https://codepen.io/tommedema/pen/xxbXBRe

In Chrome 79.0.3945.79 on MacOS Catalina 10.15.2 this renders as:

Chrome 79.0.3945.79

Clearly it's not visually horizontally centered. Yet in other browsers like Safari and Firefox 71 it is:

Firefox 71

Regarding Carol's answer of using font-size and box-sizing, the result is still the same. I've selected the emoji/text so you can more clearly see the issue of there being whitespace to the right of the emoji, but only on Chrome and not on other browsers:

Chrome with box-sizing

like image 779
Tom Avatar asked Jan 02 '20 04:01

Tom


2 Answers

This appears to be an old Chromium rendering bug that specifically affects Retina devices. That might explain why some other posters are suggesting solutions that don't work for you!

See the bug report here: https://bugs.chromium.org/p/chromium/issues/detail?id=551420. There's no ETA on a fix, of course...

I have stumbled across something interesting playing around with font sizes though. At larger font sizes (approx 22px in my testing, but this might be dependent on a variety of factors), the problem goes away entirely.

Therefore, my suggested fix is a bit of a workaround, but should be safe for other browsers too. Double the font size, but scale it down again using transform:

.avatar {
  font-size: 30px;  /* double the size you wanted */
  ...
}

.avatar div {
  transform: scale(0.5);  /* reduce size by 50%, back to originally intended size */
}
like image 168
gwcodes Avatar answered Sep 28 '22 01:09

gwcodes


The default line-height of each browser is different.

Use standard line-height: 1; explicitly.

https://codepen.io/boralp/pen/wvByBXy

.avatar {
  width: 30px;

  font-size: 15px;
  box-sizing: content-box;

  line-height: 1;
  padding: 10px;
  background-color: #eee;
  border-radius: 50%;

  display: grid;
  justify-items: center;
  align-items: center;
}
like image 22
Bora Alp Arat Avatar answered Sep 27 '22 23:09

Bora Alp Arat