I need to load fonts (.eot,.ttf etc) on demand as per the requirement.
WebFont.load({
custom: {
families: ['Font1'],
urls: ['css-path']
}
});
I am unable to do it using above approach.
One of the solution i found out to create style element and add the #font-face like this -
const cssStr = `
#font-face {
font-family: Tondo;
src: url(../static-assets/common/fonts/tondo/tondo-light-webfont.eot);
}`
const style = document.createElement('style');
style.innerHTML = cssStr;
document.head.appendChild( style );
Is there any better way to do it?
Related
I have a certain frontend code that is deployed in another website through a specific div.
Our assets, like images and such, are made available in different urls, based on the environment (dev, staging and production).
In the code, I used window.location.href to obtain the current url to discover in which environment I am:
export const buildImagePath = (resource_path:string):string => {
var url = window.location.href;
if (url.includes(".staging.") )
return "https://staging.something.com"+"/"+resource_path ;
else #production
return "https://something.com" +"/"+resource_path;
return resource_path;
}
, and then gave each image a class id, and added the following code
ngOnInit(): void {
var imgs =document.getElementsByClassName("img_class_X") as HTMLCollectionOf<HTMLImageElement>| null;
if (imgs!=null)
for(var i = 0; i < imgs.length; i++) {
if (imgs[i]!=null)
imgs[i].src = buildImagePath('assets/imgs/icons/X.svg');
}
}
And this works - except for some hardcoded paths in have in a styles.scss file: urls for website fonts.
How can I had the logic there as well? Meaning, how to make the code conditionally load the fonts from staging.something.com/assets/fonts... or something.com/assets/fonts/... based on the enviroment, for this file:
styles.scss:
/ For more information: https://material.angular.io/guide/theming
#use "~#angular/material" as mat;
$fontpath: "https://something.com/assets/fonts/";
#font-face {
font-family: "my cool font";
src: url($fontpath + "mycoolfont.woff2") format("woff2"),
url($fontpath + "mycoolfont.woff") format("woff");
font-weight: bold;
font-style: normal;
}
My application is built using NextJs and uses Chakra UI.
I have installed Google Fonts by following this
chakra Google fonts
npm install #fontsource/open-sans #fontsource/raleway
import { extendTheme } from "#chakra-ui/react"
const theme = extendTheme({
fonts: {
heading: "Open Sans",
body: "Raleway",
},
})
export default theme
Now I can use two different fonts,
For Body
For headings
However, how about using more fonts ?
Say I was to use different fonts for Buttons,
Different for Text.
Also within text, I want to use different fonts for Italic and underlined text portions.
How do I do that ?
It is pretty easy to add more fonts using the theme, you just need to add them in fonts: {} and then you can reference them by using the chakra variable: var(--chakra-fonts-xxx)
For example, if you want to define a font dedicated to subheader:
import { extendTheme } from "#chakra-ui/react";
const theme = extendTheme({
fonts: {
heading: "Open Sans",
subHeading: "Times New Roman",
body: "Arial Black",
},
textStyles: {
h2: {
'font-family': 'var(--chakra-fonts-subHeading)',
},
}
});
export default theme;
Now when you'll create a h2 component (<Heading as="h2">h2 text</Heading>), it will use this font.
You'll notice that unfortunately, I had to use 'font-family' instead of fontFamily (it seems to be an existing bug, same for font-weight).
To use different fonts in Buttons, you can customize Buttons components from your theme.
in const theme, the same way as fonts you need to create a components object:
const theme = extendTheme({
fonts: {
heading: "Open Sans", body: "Raleway",
},
components: {
Button: {
baseStyle: {
fontFamily: 'yourfont here'
}
}
}
})
You can do the same with other state of buttons for example _hover, _focus, _isDisabled, etc.
Similar question but the same: How to remove default Storybook Canvas styles?
The default font fam used in Storybook is:
font-family: "Nunito Sans", -apple-system, ".SFNSText-Regular", "San Francisco", BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Helvetica, Arial, sans-serif;
But this is overriding a lot of my apps fonts as the dont is applied to a class at the element level. See the pic:
How can this be turned off?
(this is vue with buefy component lib)
You can add custom styling to every different element that storybook renders, in .storybook/preview.ts. You can apply an empty style like below (or your own defined style with your own font) and it will not load the custom generated styling.
import { styled } from '#storybook/theming';
const divEmpty = styled.div(({ theme }) => ({
}));
const pEmpty = styled.p(({ theme }) => ({
//example of custom font
fontFamily: "Arial"
}));
const spanEmpty = styled.span(({ theme }) => ({
}));
const inputEmpty = styled.input(({ theme }) => ({
}));
export const parameters = {
...
docs: {
components: {
p: pEmpty,
div: divEmpty,
span: spanEmpty,
input: inputEmpty
},
},
}
First off, you can't remove ALL of the styles of Storybook. Otherwise you'll have to design the sidebar and all the buttons yourself. Those styles in your screenshot are only applying to the docs generated by Storybook, not your own components. They're attached to class sbdocs. For example:
sbdocs-p instead of p,
sbdocs-h1 instead of h1
etc. If you want to override them, why not simply override them like this?
p, .sbdocs-p{
font-family:inherit;
}
h1, .sbdocs-h1{
font-family:inherit;
}
etc.
I want to be able to choose font I wish to download from backend via select and then use it in my project. User can change fonts and download new ones. I have problem that if font is fixed in my css like this:
export const MainContent = styled.div`
#font-face {
font-family: 'Lobster';
src: local('Font Name'), local('FontName'),
url ('http://localhost/font/lobster') format('woff');
font-weight: bold;
font-style: normal;
font-display: swap;
};
font-family: 'Lobster';
`;
It is downloaded properly right after app starts and I can use it, however I don't want to have it fixed, tried few solutions so far like with WebFont:
import WebFont from 'webfontloader';
function App() {
enter code here
WebFont.load({
custom: {
families: ['Lobster'],
urls: ['http://localhost/font/${fontname'] <= used fixed lobster in this case
}
});
...
}
But it throws error like =
The resource from “http://localhost/font/lobster” was blocked due to MIME type (“font/ttf”) mismatch (X-Content-Type-Options: nosniff).
another idea was to send parameter which could replace for example lobster via props of styled component like
<MainContent fontName="lobsterTheSecond">
...
</MainContent>
However I don't really know how to pass props in #font-face as it keeps throwing errors.
Does anyone knows how can I add fonts dynamically from backend while app works? I'm out of ideas already
Not sure about WebFont but it can be done quite easy with styled components:
First of all don't pass it to your 'MainContent' but rather pass props with new font to your globalStyles and then do something like that:
const GlobalStyle = createGlobalStyle`
body {
#font-face {
font-family: 'Lobster';
src: `${props =>
url ('http://localhost/font/${props.fontName}')` format('woff');
font-weight: bold;
font-style: normal;
font-display: swap;
};
}
`
and pass it like:
function App() {
const [newFont, setNewFont] = useState('');
return (
<div>
<GlobalStyle fontName{newFont} />
<button onClick={() => setNewFont('myNewFont')>Click</button>
</div>
)
}
and then in your MainContent just use this font:
const MainContent = styled.div`
font-family: 'Lobster';
`
I'm trying to use gulp-iconfont to build an icon font from a set of svg images.
I've created my gulp task and there're no errors when I run it. But neither can I get the code for each icon, which is what I need to use the icons on css pseudoelements.
The console output shows strange characters where the unicode is supposed to be:
Here's my gulp task:
gulp.task('iconfont', function(){
gulp.src(['assets/icons/*.svg'])
.pipe(iconfont({
fontName: 'icon-font', // required
appendUnicode: true, // recommended option
normalize: true,
centerHorizontally: true,
fontHeight: 100,
formats: ['ttf', 'eot', 'woff'],
}))
.on('glyphs', function(glyphs, options) {
console.log(glyphs, options);
})
.pipe(gulp.dest('assets/fonts/'));
});
As the appendUnicode option is set to true, I can see it at the beggining of my svg file name, for example uEA02-calendar.svg.
However, if I try to use it on my css file:
.calendar:before {
content: "uEA02";
speak: none;
font-style: normal;
font-weight: normal;
font-family: "icon-font"; }
what I see is the text uEA02 instead of my icon. I've checked and the font is loading, I don't know what could I be missing here?
I usually pair gulp-iconfont with gulp-iconfont-css. This additional package exports a stylesheet with the appropriate entities binded to a class. You can export pre-processed css or vanilla css.
Here's my gulp task.
var iconfont = require('gulp-iconfont');
var iconfontCss = require('gulp-iconfont-css');
var glyphFontName = 'icon';
var stream = gulp.src('resources/assets/glyph/*.svg')
.pipe(iconfontCss({
fontName: glyphFontName,
path: 'node_modules/gulp-iconfont-css/templates/_icons.scss',
targetPath: '../../resources/sass/generated/' + glyphFontName + '.scss',
fontPath: '../fonts/',
cssClass: 'i',
centerHorizontally: true
}))
.pipe(iconfont({
fontName: glyphFontName,
formats: [
'ttf',
'eot',
'woff',
'woff2'
],
}))
.pipe(gulp.dest('public/fonts/'));
return stream;
You simply need to escape the unicode string with a backslash (\).
In your CSS just write:
.calendar:before {
content: "\EA02";
speak: none;
font-style: normal;
font-weight: normal;
font-family: "icon-font";
}
You need to reformat the unicode from within the function you're passing to the "on glyphs" event. Otherwise the unicode will be lost in templating.
I'd suggest something like this:
.on('glyphs', function(glyphs, options) {
glyphs = glyphs.map((glyph) => {
...glyph,
unicode: glyph.unicode[0].codePointAt(0).toString(16).toUpperCase()
});
console.log(glyphs, options);
})
Can't take credit for this solution - found the answer in this post