Use Local Font in Next.js - css

I'm struggling to get a local font to work on my Next.js website and can't seem to find much on it. I used #font-face in my globals.css style-sheet. (I referenced https://kirazhang.com/posts/nextjs-custom-fonts).
#font-face {
font-family: "Adobe Caslon Pro";
src: url("/static/fonts/ACaslonPro-Regular.otf") format("opentype");
font-style: medium;
font-display: swap;
}
then in _app.js
import "../styles/globals.css";
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default MyApp;
I also added a _document.js file to my pages folder
import Document, { Html, Head, Main, NextScript } from "next/document";
class MyDocument extends Document {
static async getInitialProps(ctx) {
const initialProps = await Document.getInitialProps(ctx);
return { ...initialProps };
}
render() {
return (
<Html>
<Head />
<link
rel="preload"
href="/static/fonts/ACaslonPro-Regular.otf"
as="font"
crossOrigin=""
/>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
When everything is said and done it gives me Times in New Roman when I inspect the webpage.

I think the installation of your font is good, but you have to call a class/className or style with this font-family inside your component.
Exemple:
<div style={{fontFamily: "Adobe Caslon Pro"}} >
Exemple
</div>

Related

Why are my tailwind css classes not working?

Hi i am new to tailwind css, i am trying to do a portfolio website with next js tailwind css but my classes are not working and i do not know why.
tailwind.config.js:
/** #type {import('tailwindcss').Config} */
module.exports = {
content: ["./src/**/*.{html,js}"],
theme: {
extend: {},
},
plugins: [],
}
This are my globals.css:
#import "tailwindcss/base";
#import "tailwindcss/components";
#import "tailwindcss/utilities";
html,
body {
padding: 0;
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
}
a {
color: inherit;
text-decoration: none;
}
* {
box-sizing: border-box;
}
#font-face {
font-family: "burtons";
src: url("../public/Burtons.otf");
}
And this is my index.tsx:
import Head from 'next/head'
import { Inter } from '#next/font/google'
import { BsFillMoonStarsFill } from 'react-icons/bs';
const inter = Inter({ subsets: ['latin'] })
export default function Home() {
return (
<>
<Head>
<title>Mateo Ghidini Dev</title>
<meta name="description" content="Generated by create next app" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className='bg-white px-10'>
<section className='min-h-screen'>
<nav className='py-10 mb-12 flex justify-between'>
<h1 className='text-xl'>Developed by Mateo Ghidini</h1>
<ul className='flex items-center'>
<li>
<BsFillMoonStarsFill/>
</li>
<li>Resume</li>
</ul>
</nav>
</section>
</main>
</>
)
}
Only my html tags are working. Any reason why?
If the classes are working in your HTML tags then the problem must be the content array in your tailwind.config.js. You are adding tailwind classes in a file whose path is not included in the content array so Tailwind is likely purging those classes and not applying them.
Modify it like this and try:
module.exports = {
content: ["./src/**/*.{html,js,tsx}"],
theme: {
extend: {},
},
plugins: [],
}
Also make sure that your index file or any other file where you are applying the classes are inside src folder and if you want to target other folders like pages in case of next.js then mention their paths too in the content array.
I guess your tailwind classes don't get shipped. Please have a look at the Tailwind docs for that, you can either use the tailwind CLI in a manual approach or use PostCSS if you're not using a framework like next.js:
https://tailwindcss.com/docs/installation

NextJs Tailwind Google Font not working when weights are selected

I am trying to add a google font to NextJS via CDN. For some reason it works, but only when I add the font without selecting any font weights. Does anyone know how I can include the full font family?
Works:
<link href="https://fonts.googleapis.com/css2?family=Inter&display=swap"rel="stylesheet"/>
Does not work:
<link href="https://fonts.googleapis.com/css2?family=Inter:wght#100;200;300;400;500;600;700;800;900&display=swap" rel="stylesheet"/>
Full _document.tsx
import Document, {
DocumentContext,
DocumentInitialProps,
Html,
Head,
Main,
NextScript,
} from "next/document";
class MyDocument extends Document {
static async getInitialProps(
ctx: DocumentContext
): Promise<DocumentInitialProps> {
const initialProps = await Document.getInitialProps(ctx);
return initialProps;
}
render() {
return (
<Html>
<Head>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link
rel="preconnect"
href="https://fonts.gstatic.com"
crossOrigin="true"
/>
{/* <link
href="https://fonts.googleapis.com/css2?family=Inter&display=swap"
rel="stylesheet"
/> */}
<link href="https://fonts.googleapis.com/css2?family=Inter:wght#100;200;300;400;500;600;700;800;900&display=swap" rel="stylesheet"/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
tailwind.config.js
/** #type {import('tailwindcss').Config} */
const defaultTheme = require("tailwindcss/defaultTheme");
const headerHeight = "80px";
module.exports = {
content: [
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
"./layouts/**/*.{js,ts,jsx,tsx}",
"node_modules/daisyui/dist/**/*.js",
],
theme: {
extend: {
fontFamily: {
sans: ["Inter", ...defaultTheme.fontFamily.sans],
},
height: {
header: headerHeight,
},
padding: {
header: headerHeight,
},
},
},
plugins: [require("daisyui"), require("#tailwindcss/typography")],
};
#import url("https://fonts.googleapis.com/css2?family=Inter:wght#100;200;300;400;500;600;700;800;900&display=swap");
#tailwind base;
#tailwind components;
#tailwind utilities;
html,
body,
#__next {
padding: 0;
margin: 0;
height: 100%;
}
a {
color: inherit;
text-decoration: none;
}
* {
box-sizing: border-box;
}
Method 1
For the google font to work,
Go to Google Fonts and select the font you want in your app, like here I am using Dancing Script with all weights.
Now copy the import URL given in Use on the web section.
#import url('https://fonts.googleapis.com/css2?family=Dancing+Script:wght#400;500;600;700&display=swap');
Paste the import in globals.css file like this.
#import url('https://fonts.googleapis.com/css2?family=Dancing+Script:wght#400;500;600;700&display=swap');
#tailwind base;
#tailwind components;
#tailwind utilities;
IN tailwind.config.js file , Inside themes => extend add a new property of fontFamily and give the font a name like Dancing here.
theme: {
extend: {
fontFamily: {
Dancing: ['Dancing Script', 'cursive'],
},
},
},
Note: The rules in the array should be the same as given in Google fonts.
Now you can give any tag the className of font-fontName in this case font-Dancing.
<h1 className="font-Dancing">This is using a custom font</h1>
Method 2
Try to use the font-bold class in the code as an alternative.

Why are my styles not getting applied to elements in nextjs?

I have added the following classes to elements as follows:
import Link from "next/link";
import React from "react";
const Page = () => {
return (
<div>
<h1 className="notes-header">Index Page</h1>
<Link href="./notes">
<a className="notes-home">Notes</a>
</Link>
</div>
);
};
export default Page;
Next, I added styling to my element as follows
.notes-header {
font-size: 100px;
}
.notes-home {
font-size: 28px;
}
Lastly, I created a _app.js file and imported the global css file as shown below:
import React from "react";
import "../styles/globals.css";
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
The problem is my styles don't get applied to my selected elements. What I'm I getting wrong?

katex math is not rendering perfectly in react

React code
import React from "react";
import katex from "katex/dist/katex.mjs";
export default function App() {
return (
<div
dangerouslySetInnerHTML={{
__html: katex.renderToString("\\sum_{i=0}^{n-1}A[i]"),
}}
/>
);
}
/public/index.html
Included style
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex#0.13.18/dist/katex.min.css" integrity="sha384-zTROYFVGOfTw7JV7KUu8udsvW2fx4lWOsCEDqhBreBwlHI4ioVRtmIvEThzJHGET" crossorigin="anonymous">
Output
Expected output
Can anyone tell me that what mistake is here?
Answer to my question
const html = katex.renderToString(str, {
throwOnError: false,
displayMode: true // make it true
})
.katex-display,.katex-display > .katex, .katex-display > .katex > .katex-html {
display: inline !important;
// make it inline, so it can render with your text even after `displayMode:true`
}
.katex-display{
text-align:left !important;
}
.katex-display>.katex{
text-align:left !important;
}

Can't import Google Fonts with Styled Components and Next.js

I'm having the following issue when trying to load Google Fonts. I read that I'm supposed to write something like this in _document.js to import it inside a head tag
import React from 'react';
import Document, { Html, Head, Main, NextScript } from 'next/document';
class MyDocument extends Document {
render() {
return (
<Html lang="en">
<Head>
<link
rel="preload"
href="/fonts/noto-sans-v9-latin-regular.woff2"
as="font"
crossOrigin=""
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
but this is the code I had to use to make Styled Components work with Next.js
import Document, { DocumentContext } from 'next/document';
import { ServerStyleSheet } from 'styled-components';
export default class MyDocument extends Document {
static async getInitialProps(ctx: DocumentContext) {
const sheet = new ServerStyleSheet();
const originalRenderPage = ctx.renderPage;
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />),
});
const initialProps = await Document.getInitialProps(ctx);
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
),
};
} finally {
sheet.seal();
}
}
}
So my question is: how can I modify my _document.js file to use the styles of Google Fonts?
Also, if it's of any help, this is the GlobalStyle I'm using and that doesn't import the fonts
import { createGlobalStyle } from '#xstyled/styled-components';
const GlobalStyle = createGlobalStyle`
#import url('https://fonts.googleapis.com/css2?family=Lato&family=Rubik&display=swap');
* {
margin: 0;
padding: 0;
}
*,
*::before,
*::after {
box-sizing: inherit;
}
html {
box-sizing: border-box;
font-size: 62.5%;
position: relative;
background: grey;
}
body {
font-family: 'Lato', sans-serif;
}
`;
const BasicLayout = ({ children }: { children: any }) => {
return (
<>
<GlobalStyle />
{children}
</>
);
};
export default BasicLayout;
Head to this page.
https://nextjs.org/docs/advanced-features/custom-app
Please read about custom _app.js and then do as following:
First, You need to create a custom _app.js for your app. (This must be in the root of your pages directory)
Then you need to create _app.css in the same directory
Then import the css file into your _app.js
import "./_app.css";
Then in your _app.css file, import your google font like the following:
#import url("https://fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&display=swap");
in the css file and in the body tag add the following line:
body {
font-family: "PT Sans Narrow", sans-serif;
etc..
}
I came across the same issue, but wasn't a fun of Hooman's answer as that requires the need of having a .css file only to contain the google font import.
Instead, here's the proper way to load your fonts while using styled-components:
import Document, {
Html,
Head,
Main,
NextScript,
DocumentContext,
DocumentInitialProps,
} from "next/document";
import { ServerStyleSheet } from "styled-components";
class MyDocument extends Document {
// Load styles before rendering
static async getInitialProps(ctx: DocumentContext): Promise<DocumentInitialProps> {
const sheet = new ServerStyleSheet();
const originalRenderPage = ctx.renderPage;
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />),
});
const initialProps = await Document.getInitialProps(ctx);
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
),
};
} finally {
sheet.seal();
}
}
render() {
return (
<Html lang="en">
<Head>
{/* Google Fonts */}
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="anonymous" />
<link
href="https://fonts.googleapis.com/css2?family=Libre+Franklin:wght#400;500&display=swap"
rel="stylesheet"
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
Make sure your render method is not defined as static.

Resources