stencil
stencil copied to clipboard
StencilJS Custom Fonts not working
Stencil version:
@stencil/[email protected]
I'm submitting a:
[x] bug report [ ] feature request [] support request => Please do not submit support requests here, use one of these channels: https://stencil-worldwide.herokuapp.com/ or https://forum.ionicframework.com/
Current behavior:
Importing a custom font with the path: url(assets/fonts/FONTNAME.woff) However the Font Family does not appear. It seems like it just cannot get the path correct? I have tried a lot, ../assets, ../src/assets/ /dist/collection/assets etc, still the font is not being applied to my text.
Expected behavior:
The CSS using font-family: CUSTOMFONT would load and the text would have the custom font given.
Sorry to bring bad news but as far as I know, there's currently no way to load custom fonts at all from within a shadow DOM. If you want to hack around the issue you can inject the required css into the <head>
tag on component load.
Chrome bug report https://bugs.chromium.org/p/chromium/issues/detail?id=336876
hi, any work arounds for this
You can dynamically inject your CSS into the <head>
tag as I suggested.
Something like this should work:
componentDidLoad() {
// Add custom font to page DOM since font-face doesn't work within Shadow DOM.
const fontCssUrl = 'https://example.com/font.css';
let element = document.querySelector(`link[href="${fontCssUrl}"]`);
// Only inject the element if it's not yet present
if (!element) {
element = document.createElement('link');
element.setAttribute('rel', 'stylesheet');
element.setAttribute('href', fontCssUrl);
document.head.appendChild(element);
}
}
how to include google fonts here now, limited to particular web component? any help please? :(
Update:
@richrd it worked! tysm
There seems to be another workaround: https://github.com/google/material-design-icons/issues/1165#issuecomment-851128010
Basically, you put the same @import url('-------');
in both app.css and the my-components.css
By the way this is not a StencilJS bug but for me those solutions work flawless. I wrote a detailed solution here: https://stackoverflow.com/a/57623658/8196542
@richrd , This workaround : https://github.com/ionic-team/stencil/issues/2072#issuecomment-588465875, also works only if shadow
prop in the Component decorator is false. Any way to make it work with shadow DOM set to true
Thanks @ChrisMeye for this in depth solution, I will raise a PR for the Stencil docs to provide more guidance for our general audience.
It looks like Stencil already recommends using global styles for things like:
- Theming: defining CSS variables used across the app
- Load fonts with @font-face
- App wide font-family
- CSS resets
@ChrisMeye it seems like this matches what you have outlined in Option 1. In what circumstances are Option 2 and Option 3 better alternatives than using global styles? Any feedback would be appreciated!