Thuta Learning
Next.js
BasicWeb DevelopmentIntermediate

CSS, Images, and Fonts

Next.jsLesson 630 min

What you'll walk away with

  • Keep site-wide styles in globals.css and component styles in .module.css files
  • Use next/image correctly with width/height, a static import or fill
  • Allow remote images with remotePatterns in next.config.ts
  • Load a Latin and a Myanmar font with next/font without layout shift

Explain it simply

Explain it simply

Knowing CSS is not enough to make a UI look good. In production you also have to prevent a phone from downloading a 4000-pixel image, text jumping down when an image arrives, and letters suddenly changing shape once a font finishes loading.

Next.js helps with all of this at the framework level. CSS Modules stop class names from colliding, next/image knows an image's size in advance and sends a size that suits the device, and next/font serves fonts from your own site, prepared at build time.

Problem → Why → Solution

The problem: an image without a size and colliding class names

The note card uses a plain <img> without width or height. Until the file downloads the browser does not know how much space to reserve, draws it at height 0, and when the picture arrives the text below jumps down. This is called layout shift (CLS). The file is also a 3 MB photo straight from a camera, so it is slow on a phone.

Meanwhile two components each define a .cover class in globals.css, the later rule overrides the earlier one, and one card's image suddenly grows.

components/note-card.tsx
// No size: the browser reserves no space, then the text jumps
export function NoteCard() {
  return (
    <article className="card">
      <img src="/notebook-original.jpg" className="cover" />
      <h2>What I learned today</h2>
    </article>
  );
}
/* globals.css: .cover is also defined by ProfileCard further down
   the file, and the later rule wins for both components */

Why does this happen?

A browser can only know an image's aspect ratio in advance from its width and height attributes; without them it cannot reserve space. Class names in global CSS all share one namespace for the whole page, so two components that pick the same name collide. next/image insists on a size, and CSS Modules rewrite each class into a unique name per file, which removes both problems.

Core concept: two places for styles, and how the framework handles images and fonts

Import globals.css from the root layout and keep only site-wide styles there: resets, colour variables, the body font, heading sizes. Styles that belong to a single component go in a .module.css file such as note-card.module.css; you import it with import styles from "./note-card.module.css" and apply className={styles.card}. At build time Next.js rewrites .card into a name that is unique to that file, so it can never collide with another component's .card. The create-next-app defaults may also set up Tailwind CSS for you, and it mixes fine with CSS Modules.

The <Image> component from next/image replaces <img> and does three jobs. First, it knows the aspect ratio from width and height (or fill), so the browser reserves space and nothing shifts. Second, it generates a srcset of several sizes for different screens and serves a smaller format such as WebP when the browser supports it. Third, it lazy-loads images that are not on screen yet.

When you pass an image from public as a string such as "/notebook.jpg", you write width and height yourself. With a static import such as import cover from "./notebook.jpg", Next.js reads the size at build time, and placeholder="blur" becomes available. To make an image fill its parent box, use fill and give the parent position: relative plus a sizes prop on the image. Images from another server must be allowed in images.remotePatterns in next.config.ts.

next/font downloads Google Fonts or local font files at build time and serves them from your own site, so the browser sends no request to Google. It also adjusts the fallback font's size so lines do not jump when the real font swaps in. Fonts that are not variable fonts need explicit weights, and you choose which subsets, such as latin or myanmar, you need.

Mental model: what goes where
  1. Site-wide styles go in globals.css
  2. Component styles go in .module.css
  3. Images use <Image> with a size
  4. Fonts load via next/font in a layout

If only one component uses a style, keep it in a module; every rule that lands in globals raises the chance of a collision.

General pattern

tsx
import Image from "next/image";
import styles from "./component-name.module.css";

<div className={styles.className}>
  <Image src="/file.jpg" alt="what the image shows" width={W} height={H} />
  <Image src={importedImage} alt="..." />          {/* size read at build */}
  <div style={{ position: "relative" }}>
    <Image src="/file.jpg" alt="..." fill sizes="100vw" />
  </div>
</div>

A CSS Module is imported as an object and used as styles.className. <Image> always needs alt, and there are three ways to give it a size: write width/height yourself, use a static import, or use fill inside a positioned parent.

Example: a NoteCard with an image

This component shows public/notebook.jpg with <Image> and takes its styles from note-card.module.css. The CSS file itself is shown in the section after the example.

tsx
import Image from "next/image";
import styles from "./note-card.module.css";

export function NoteCard() {
  return (
    <article className={styles.card}>
      <Image
        src="/notebook.jpg"
        width={640}
        height={360}
        alt="A notebook on a desk"
        className={styles.cover}
      />
      <h2>What I learned today</h2>
    </article>
  );
}

Code breakdown

  1. Importsimport styles from "./note-card.module.css";

    Importing a CSS Module gives you an object of class names. The real value of styles.card is a unique class string generated at build time.

  2. srcsrc="/notebook.jpg"

    public/notebook.jpg is referenced as /notebook.jpg. Because src is a string, Next.js cannot know the image's size by itself.

  3. Sizewidth={640}

    width={640} with height={360} states a 16:9 aspect ratio, so the browser reserves space before the image arrives. They are not the exact displayed pixels; CSS can still make the image responsive.

  4. altalt="A notebook on a desk"

    Describes what the picture shows for users who cannot see it. Do not write "image" or the file name; for a purely decorative image use alt="".

  5. Scoped classclassName={styles.cover}

    <Image> accepts className too. styles.cover is this module's cover only, so it never clashes with another component's .cover.

You should see
A note card appears with a stable size and an optimized image.

The CSS Module file and a responsive image

Even with width and height attributes, giving the image width: 100% and height: auto in CSS lets it shrink and grow with the card while keeping its aspect ratio.

components/note-card.module.css
.card {
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  overflow: hidden;
}

.cover {
  width: 100%;
  height: auto;
}

Latin and Myanmar fonts with next/font

Myanmar Notes contains both English and Myanmar text, so it needs two fonts. Each font is exposed as a CSS variable and listed in order in the font-family stack in globals.css. Noto Sans Myanmar is not a variable font, so its weights must be listed.

app/layout.tsx
import { Inter, Noto_Sans_Myanmar } from "next/font/google";
import "./globals.css";

const latin = Inter({ subsets: ["latin"], variable: "--font-latin" });
const myanmar = Noto_Sans_Myanmar({
  subsets: ["myanmar"],
  weight: ["400", "700"],
  variable: "--font-myanmar",
});

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="my" className={`${latin.variable} ${myanmar.variable}`}>
      <body>{children}</body>
    </html>
  );
}
// globals.css: body { font-family: var(--font-latin), var(--font-myanmar), sans-serif; }

Allowing remote images

To use an image from a CMS or a storage bucket in <Image>, allow its hostname in next.config.ts. The list stops anyone from using your server to optimise images from arbitrary sites. Restart the dev server after changing the config.

next.config.ts
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  images: {
    remotePatterns: [{ protocol: "https", hostname: "images.example.com" }],
  },
};

export default nextConfig;

In real projects

In real projects

E-commerce product lists contain hundreds of images. <Image> loads them only as they approach the screen and sends small sizes to phones, which cuts data use and load time noticeably. Google's Core Web Vitals measure layout shift (CLS) and when the largest content appears (LCP), so correct image sizing affects both search ranking and user experience. An image visible immediately, such as a hero image at the top, should be preloaded instead of lazy-loaded; Next.js 15 uses the priority prop for this, and the API has been evolving, so check the Image docs for your version.

Teams often keep design tokens such as colours and spacing as CSS variables in globals.css, and component modules reuse them as var(--color-primary). Changing the brand colour then means editing one place, while component styles stay isolated from each other.

Common mistakes

Common mistakes

1. Giving <Image> neither width/height nor fill

Passing a string src without a size, as in <Image src="/notebook.jpg" alt="..." />, makes Next.js report that the width property is required. Add width and height, use a static import, or use fill inside a parent with position: relative. With fill, leaving out sizes makes the browser assume the image is as wide as the screen, so it may download a larger file than needed.

2. Dumping every component's styles into globals.css

globals.css loads on every page and all its class names share one namespace, so the bigger it grows, the more names such as .title and .card collide. Move styles that belong to one component into a .module.css file next to it.

3. Using a remote image without configuring it

Using src="https://images.example.com/a.jpg" without remotePatterns fails with an error saying the hostname is not configured in next.config. Add that exact hostname rather than a broad wildcard.

Mini challenge

Mini challenge: a profile card

Write a ProfileCard component for a team page. The photo must fill a square box, and the styles must live in a CSS Module.

  • The Profile type has name, role and photo (a path in the public folder)
  • The image uses fill inside a box with position: relative and aspect-ratio: 1 / 1
  • Add a sizes prop, and include the person's name in alt
  • app/team/page.tsx renders one card
components/profile-card.tsx + app/team/page.tsx
// components/profile-card.tsx
import Image from "next/image";
import styles from "./profile-card.module.css";

type Profile = {
  // TODO: name, role, photo
};

export function ProfileCard(/* TODO: profile prop */) {
  // TODO: <article> with a photo box (fill image), the name and the role
}

// app/team/page.tsx
// TODO: import ProfileCard and render it with one profile

/* profile-card.module.css
   TODO: .card, .photoBox (relative, square), .photo (object-fit) */

Expected: /team shows a card with a square photo (alt "Portrait of Su Su"), the heading "Su Su" and the line "Editor". Resizing the browser keeps the photo square.

Show hint

A fill image fills its nearest positioned parent. Add object-fit: cover to the .photo class so the picture is not stretched. For a card about 300px wide, sizes="(max-width: 600px) 100vw, 300px" works.

Show solution
components/profile-card.tsx + app/team/page.tsx
// components/profile-card.tsx
import Image from "next/image";
import styles from "./profile-card.module.css";

export type Profile = {
  name: string;
  role: string;
  photo: string;
};

export function ProfileCard({ profile }: { profile: Profile }) {
  return (
    <article className={styles.card}>
      <div className={styles.photoBox}>
        <Image
          src={profile.photo}
          alt={`Portrait of ${profile.name}`}
          fill
          sizes="(max-width: 600px) 100vw, 300px"
          className={styles.photo}
        />
      </div>
      <h2>{profile.name}</h2>
      <p>{profile.role}</p>
    </article>
  );
}

// app/team/page.tsx
import { ProfileCard } from "../../components/profile-card";

export default function TeamPage() {
  return (
    <ProfileCard profile={{ name: "Su Su", role: "Editor", photo: "/team/su-su.jpg" }} />
  );
}

/* components/profile-card.module.css
.card { max-width: 300px; border-radius: 12px; overflow: hidden; }
.photoBox { position: relative; aspect-ratio: 1 / 1; }
.photo { object-fit: cover; }
*/

Quick quiz 1 / 3

What happens with <Image src="/notebook.jpg" alt="Notebook" /> and no width, height or fill?

Quick quiz 2 / 3

NoteCard and ProfileCard each define a .title class in their own .module.css. What happens?

Quick quiz 3 / 3

An image using <Image fill /> covers the whole page. What is the most likely cause?

What to remember

  • Keep site-wide styles in globals.css, imported from the root layout, and component styles in .module.css files.
  • <Image> reserves space from its size and serves device-sized, modern-format, lazy-loaded images; it always needs alt and a size (width/height, a static import or fill).
  • With fill, give the parent position: relative and the image a sizes prop, and configure remotePatterns for remote images.
  • next/font serves fonts from your own site, prepared at build time, to reduce layout shift; pick a font with the myanmar subset for Myanmar text.

Next.js — Image Optimization — Next.js

Next.js — Image Optimization — Next.js

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

CSS, Images, and Fonts | Thuta Learning