> ## Documentation Index
> Fetch the complete documentation index at: https://resources.latex-cloud-studio.com/llms.txt
> Use this file to discover all available pages before exploring further.

# LaTeX Fonts Guide: Change Font Family, Size, and System Fonts

> Learn how to change fonts in LaTeX with pdfLaTeX, XeLaTeX, and LuaLaTeX. Covers font families, fontspec, system fonts, and font packages.

export const RenderedOutput = ({title = "Rendered output", ctaHref, ctaLabel = "Open LaTeX Cloud Studio", children}) => {
  const [isExpanded, setIsExpanded] = useState(false);
  const trackEditorCta = () => {
    const target = new URL(ctaHref, window.location.href);
    globalThis.posthog?.capture?.("docs_app_cta_clicked", {
      source_page: window.location.pathname,
      source_section: "rendered_output",
      cta_variant: "first_compiled_example",
      target_url: target.toString(),
      target_utm_source: target.searchParams.get("utm_source"),
      target_utm_medium: target.searchParams.get("utm_medium"),
      target_utm_campaign: target.searchParams.get("utm_campaign"),
      target_utm_content: target.searchParams.get("utm_content")
    }, {
      transport: "sendBeacon",
      send_instantly: true
    });
  };
  return <details className="rendered-output" onToggle={event => setIsExpanded(event.currentTarget.open)}>
      <summary className="rendered-output__summary">
        <span className="rendered-output__title">{title}</span>
        <span className="rendered-output__hint" aria-hidden="true">View compiled result</span>
      </summary>
      {isExpanded && <div className="rendered-output__content">
          {children}
          {ctaHref && <aside className="rendered-output__cta" aria-label="Continue in the LaTeX editor">
              <span>
                <strong>Ready to use this syntax?</strong>
                Continue in the browser editor when you want to adapt the example in a real project.
              </span>
              <a href={ctaHref} onClick={trackEditorCta}>{ctaLabel}<span aria-hidden="true"> →</span></a>
            </aside>}
        </div>}
    </details>;
};

export const LatexSource = ({filename, source}) => {
  const [copyStatus, setCopyStatus] = useState("Copy");
  const copySource = async () => {
    try {
      await navigator.clipboard.writeText(source);
      setCopyStatus("Copied");
    } catch {
      setCopyStatus("Select and copy");
    }
  };
  return <figure className="latex-source">
      <figcaption className="latex-source__header">
        <span className="latex-source__filename">{filename}</span>
        <button type="button" className="latex-source__copy" onClick={copySource} aria-live="polite">
          {copyStatus}
        </button>
      </figcaption>
      <pre className="latex-source__pre" aria-label={`LaTeX source: ${filename}`} tabIndex="0">
        <code className="language-latex">{source}</code>
      </pre>
    </figure>;
};

export const LatexPreview = ({src, alt, caption, width, height}) => {
  const minZoom = 1;
  const maxZoom = 3;
  const zoomStep = 0.5;
  const measureSvgContent = async (assetSrc, pageWidth, pageHeight) => {
    const cacheKey = "__latexCloudSvgContentBoxCache";
    const contentBoxCache = globalThis[cacheKey] ?? new Map();
    globalThis[cacheKey] = contentBoxCache;
    if (contentBoxCache.has(assetSrc)) return contentBoxCache.get(assetSrc);
    const measurement = (async () => {
      const assetUrl = new URL(assetSrc, window.location.href);
      if (assetUrl.origin !== window.location.origin) {
        throw new Error("Rendered output must use a same-origin SVG asset.");
      }
      const response = await fetch(assetUrl, {
        credentials: "same-origin"
      });
      if (!response.ok) throw new Error(`Rendered output request failed with ${response.status}.`);
      const source = await response.text();
      const documentNode = new DOMParser().parseFromString(source, "image/svg+xml");
      if (documentNode.querySelector("parsererror")) throw new Error("Rendered output is not valid SVG.");
      const sourceSvg = documentNode.documentElement;
      sourceSvg.querySelectorAll("script, foreignObject").forEach(node => node.remove());
      [sourceSvg, ...sourceSvg.querySelectorAll("*")].forEach(node => {
        [...node.attributes].forEach(attribute => {
          if ((/^on/i).test(attribute.name)) node.removeAttribute(attribute.name);
          if ((attribute.name === "href" || attribute.name === "xlink:href") && !attribute.value.startsWith("#")) {
            node.removeAttribute(attribute.name);
          }
        });
      });
      const measurementHost = document.createElement("div");
      measurementHost.className = "latex-preview__measurement-host";
      const measuredSvg = document.importNode(sourceSvg, true);
      measuredSvg.setAttribute("aria-hidden", "true");
      measurementHost.appendChild(measuredSvg);
      document.body.appendChild(measurementHost);
      try {
        const measuredElements = [...measuredSvg.children].filter(node => !["defs", "desc", "metadata", "style", "title"].includes(node.tagName.toLowerCase()));
        const elementBounds = measuredElements.map(node => node.getBBox()).filter(box => [box.x, box.y, box.width, box.height].every(Number.isFinite) && box.width > 0 && box.height > 0);
        if (elementBounds.length === 0) {
          throw new Error("Rendered output has no measurable visible content.");
        }
        const sortedBounds = [...elementBounds].sort((left, right) => left.y - right.y);
        const clusterGap = pageHeight * 0.045;
        const clusters = [];
        sortedBounds.forEach(box => {
          const current = clusters[clusters.length - 1];
          if (!current || box.y - current.bottom > clusterGap) {
            clusters.push({
              boxes: [box],
              bottom: box.y + box.height
            });
            return;
          }
          current.boxes.push(box);
          current.bottom = Math.max(current.bottom, box.y + box.height);
        });
        const contentClusters = clusters.filter(cluster => {
          const clusterBox = cluster.boxes.reduce((combined, box) => {
            const right = Math.max(combined.x + combined.width, box.x + box.width);
            const bottom = Math.max(combined.y + combined.height, box.y + box.height);
            const x = Math.min(combined.x, box.x);
            const y = Math.min(combined.y, box.y);
            return {
              x,
              y,
              width: right - x,
              height: bottom - y
            };
          });
          const centerY = clusterBox.y + clusterBox.height / 2;
          const isMarginFurniture = cluster.boxes.length <= 2 && clusterBox.width < pageWidth * 0.2 && clusterBox.height < pageHeight * 0.04 && (centerY < pageHeight * 0.08 || centerY > pageHeight * 0.8);
          return !isMarginFurniture;
        });
        const visibleBounds = (contentClusters.length > 0 ? contentClusters : clusters).flatMap(cluster => cluster.boxes);
        const bounds = visibleBounds.reduce((combined, box) => {
          const right = Math.max(combined.x + combined.width, box.x + box.width);
          const bottom = Math.max(combined.y + combined.height, box.y + box.height);
          const x = Math.min(combined.x, box.x);
          const y = Math.min(combined.y, box.y);
          return {
            x,
            y,
            width: right - x,
            height: bottom - y
          };
        });
        const clampValue = (value, minimum, maximum) => Math.min(maximum, Math.max(minimum, value));
        const padding = Math.max(8, Math.min(pageWidth, pageHeight) * 0.025);
        const x = clampValue(bounds.x - padding, 0, pageWidth);
        const y = clampValue(bounds.y - padding, 0, pageHeight);
        const right = clampValue(bounds.x + bounds.width + padding, 0, pageWidth);
        const bottom = clampValue(bounds.y + bounds.height + padding, 0, pageHeight);
        return {
          x,
          y,
          width: right - x,
          height: bottom - y
        };
      } finally {
        measurementHost.remove();
      }
    })();
    contentBoxCache.set(assetSrc, measurement);
    measurement.catch(() => contentBoxCache.delete(assetSrc));
    return measurement;
  };
  const renderPreviewAsset = ({contentBox: assetContentBox, loading}) => {
    if (!assetContentBox) {
      return <img className="latex-preview__asset" src={src} alt={alt} width={width} height={height} loading={loading} draggable="false" />;
    }
    return <svg className="latex-preview__asset" viewBox={`${assetContentBox.x} ${assetContentBox.y} ${assetContentBox.width} ${assetContentBox.height}`} preserveAspectRatio="xMidYMid meet" role="img" aria-label={alt}>
        <image href={src} x="0" y="0" width={width} height={height} />
      </svg>;
  };
  const [isOpen, setIsOpen] = useState(false);
  const [frameMode, setFrameMode] = useState("content");
  const [viewMode, setViewMode] = useState("fit");
  const [zoom, setZoom] = useState(minZoom);
  const [contentBox, setContentBox] = useState(null);
  const [measurementStatus, setMeasurementStatus] = useState("loading");
  const dialogRef = useRef(null);
  const closeButtonRef = useRef(null);
  const viewportRef = useRef(null);
  const previousFocusRef = useRef(null);
  const dragRef = useRef(null);
  useEffect(() => {
    let isCurrent = true;
    setMeasurementStatus("loading");
    measureSvgContent(src, width, height).then(box => {
      if (!isCurrent) return;
      setContentBox(box);
      setMeasurementStatus("ready");
    }).catch(() => {
      if (!isCurrent) return;
      setContentBox(null);
      setFrameMode("page");
      setMeasurementStatus("error");
    });
    return () => {
      isCurrent = false;
    };
  }, [height, src, width]);
  const closeViewer = useCallback(() => {
    setIsOpen(false);
  }, []);
  const openViewer = () => {
    previousFocusRef.current = document.activeElement;
    setFrameMode(contentBox ? "content" : "page");
    setViewMode("fit");
    setZoom(minZoom);
    setIsOpen(true);
  };
  const applyZoom = useCallback(nextZoom => {
    const boundedZoom = Math.min(maxZoom, Math.max(minZoom, nextZoom));
    setViewMode("custom");
    setZoom(boundedZoom);
  }, []);
  const zoomIn = useCallback(() => {
    applyZoom(viewMode === "fit" ? minZoom + zoomStep : zoom + zoomStep);
  }, [applyZoom, viewMode, zoom]);
  const zoomOut = useCallback(() => {
    applyZoom(viewMode === "fit" ? minZoom : zoom - zoomStep);
  }, [applyZoom, viewMode, zoom]);
  useEffect(() => {
    if (!isOpen) return undefined;
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    closeButtonRef.current?.focus();
    return () => {
      document.body.style.overflow = previousOverflow;
      previousFocusRef.current?.focus?.();
    };
  }, [isOpen]);
  useEffect(() => {
    if (!isOpen) return undefined;
    const handleKeyDown = event => {
      if (event.key === "Escape") {
        event.preventDefault();
        closeViewer();
        return;
      }
      if ((event.key === "+" || event.key === "=") && !event.metaKey && !event.ctrlKey) {
        event.preventDefault();
        zoomIn();
        return;
      }
      if (event.key === "-" && !event.metaKey && !event.ctrlKey) {
        event.preventDefault();
        zoomOut();
        return;
      }
      if (event.key !== "Tab" || !dialogRef.current) return;
      const focusable = [...dialogRef.current.querySelectorAll('button:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])')];
      if (focusable.length === 0) return;
      const first = focusable[0];
      const last = focusable[focusable.length - 1];
      if (event.shiftKey && document.activeElement === first) {
        event.preventDefault();
        last.focus();
      } else if (!event.shiftKey && document.activeElement === last) {
        event.preventDefault();
        first.focus();
      }
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => {
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [closeViewer, isOpen, zoomIn, zoomOut]);
  const startDrag = event => {
    if (event.button !== 0 || !viewportRef.current) return;
    const viewport = viewportRef.current;
    dragRef.current = {
      pointerId: event.pointerId,
      x: event.clientX,
      y: event.clientY,
      scrollLeft: viewport.scrollLeft,
      scrollTop: viewport.scrollTop
    };
    viewport.setPointerCapture(event.pointerId);
    viewport.dataset.dragging = "true";
  };
  const continueDrag = event => {
    const drag = dragRef.current;
    const viewport = viewportRef.current;
    if (!drag || !viewport || drag.pointerId !== event.pointerId) return;
    viewport.scrollLeft = drag.scrollLeft - (event.clientX - drag.x);
    viewport.scrollTop = drag.scrollTop - (event.clientY - drag.y);
  };
  const stopDrag = event => {
    const viewport = viewportRef.current;
    if (viewport?.hasPointerCapture(event.pointerId)) viewport.releasePointerCapture(event.pointerId);
    if (viewport) delete viewport.dataset.dragging;
    dragRef.current = null;
  };
  const activeContentBox = frameMode === "content" ? contentBox : null;
  const activeWidth = activeContentBox?.width ?? width;
  const activeHeight = activeContentBox?.height ?? height;
  const activeRatio = activeWidth / activeHeight;
  const inlineContentBox = measurementStatus === "ready" ? contentBox : null;
  const inlineWidth = inlineContentBox?.width ?? width;
  const inlineHeight = inlineContentBox?.height ?? height;
  const inlineGeometry = {
    aspectRatio: `${inlineWidth} / ${inlineHeight}`,
    maxWidth: `${30 * inlineWidth / inlineHeight}rem`
  };
  const imageStyle = viewMode === "fit" ? {
    aspectRatio: `${activeWidth} / ${activeHeight}`,
    width: "100%",
    maxWidth: `${Math.max(16, activeRatio * 78)}dvh`
  } : {
    aspectRatio: `${activeWidth} / ${activeHeight}`,
    width: `${zoom * 100}%`,
    maxWidth: "none"
  };
  const zoomLabel = viewMode === "fit" ? frameMode === "content" ? "Fit content" : "Full page" : `${Math.round(zoom * 100)}%`;
  return <figure className="latex-preview">
      <button type="button" className="latex-preview__trigger" onClick={openViewer} aria-haspopup="dialog" aria-label={`Open zoomable preview: ${alt}`}>
        <span className="latex-preview__page" style={inlineGeometry}>
          {measurementStatus === "loading" ? <span className="latex-preview__loading" role="status">Preparing compiled output…</span> : renderPreviewAsset({
    src,
    alt,
    width,
    height,
    contentBox: inlineContentBox,
    loading: "lazy"
  })}
        </span>
        <span className="latex-preview__trigger-label" aria-hidden="true">
          <span className="latex-preview__trigger-icon">⌕</span>
          Open viewer
        </span>
      </button>
      <figcaption className="latex-preview__caption">
        <span>
          {caption}
          {measurementStatus === "error" && <span className="latex-preview__status" role="status"> Content fit is unavailable; the complete vector page is shown.</span>}
        </span>
        <a href={src} target="_blank" rel="noreferrer" className="latex-preview__source-link">Open SVG</a>
      </figcaption>

      {isOpen && <div className="latex-preview__backdrop" onMouseDown={event => {
    if (event.target === event.currentTarget) closeViewer();
  }}>
          <section ref={dialogRef} className="latex-preview__dialog" role="dialog" aria-modal="true" aria-label={`Rendered LaTeX viewer: ${alt}`}>
            <header className="latex-preview__toolbar">
              <div className="latex-preview__identity">
                <span className="latex-preview__eyebrow">Compiled LaTeX</span>
                <span className="latex-preview__filename">{alt}</span>
              </div>
              <div className="latex-preview__controls" aria-label="Preview controls">
                <button type="button" className={frameMode === "content" && viewMode === "fit" ? "is-active" : undefined} disabled={!contentBox} onClick={() => {
    setFrameMode("content");
    setViewMode("fit");
    setZoom(minZoom);
  }}>
                  Fit content
                </button>
                <button type="button" className={frameMode === "page" && viewMode === "fit" ? "is-active" : undefined} onClick={() => {
    setFrameMode("page");
    setViewMode("fit");
    setZoom(minZoom);
  }}>
                  Full page
                </button>
                <span className="latex-preview__zoom-group">
                  <button type="button" onClick={zoomOut} disabled={viewMode === "fit" || zoom <= minZoom} aria-label="Zoom out">−</button>
                  <output aria-live="polite" aria-label="Current zoom">{zoomLabel}</output>
                  <button type="button" onClick={zoomIn} disabled={viewMode !== "fit" && zoom >= maxZoom} aria-label="Zoom in">+</button>
                </span>
                <a href={src} target="_blank" rel="noreferrer">Open SVG</a>
                <button ref={closeButtonRef} type="button" className="latex-preview__close" onClick={closeViewer} aria-label="Close rendered LaTeX viewer">
                  Close
                </button>
              </div>
            </header>
            <div ref={viewportRef} className="latex-preview__viewport" data-view-mode={viewMode} onPointerDown={startDrag} onPointerMove={continueDrag} onPointerUp={stopDrag} onPointerCancel={stopDrag}>
              <span className="latex-preview__dialog-page" style={imageStyle}>
                {renderPreviewAsset({
    src,
    alt,
    width,
    height,
    contentBox: activeContentBox
  })}
              </span>
            </div>
            <footer className="latex-preview__viewer-note">
              Compiler-generated vector output · Use +/− to zoom · Drag to pan · Esc to close
            </footer>
          </section>
        </div>}
    </figure>;
};

If you want to change the font in LaTeX, the right method depends on your compiler. Use font packages such as `lmodern` or `newtxtext` with pdfLaTeX, and use `fontspec` with XeLaTeX or LuaLaTeX when you want system fonts such as Times New Roman, Arial, or EB Garamond.

<Info>
  **Quick answer**: use pdfLaTeX with font packages for traditional LaTeX workflows, and use XeLaTeX or LuaLaTeX with `fontspec` when you need system fonts or modern OpenType features.

  **Related topics**: [Text formatting](/learn/latex/text-formatting) | [Document classes](/learn/reference/document-classes) | [Choosing a compiler](/learn/latex/basics/choosing-compiler)
</Info>

## How to Change the Font in LaTeX

| Goal                                                    | Recommended approach                                              |
| ------------------------------------------------------- | ----------------------------------------------------------------- |
| Use a better default serif/sans/mono font with pdfLaTeX | Load a font package such as `lmodern`, `newtxtext`, or `mathpazo` |
| Use fonts installed on your computer                    | Compile with XeLaTeX or LuaLaTeX and load `fontspec`              |
| Keep math fonts consistent with text fonts              | Choose a matching text + math package pair                        |
| Improve spacing and justification                       | Add `microtype`                                                   |

## Font Basics

### The Three Font Attributes

LaTeX fonts have three independent attributes:

<LatexSource filename="font-attributes.tex" source={"\\documentclass{article}\n\\begin{document}\n\n% Family (shape of letters)\n\\textrm{Roman family (serif)}\n\\textsf{Sans serif family}\n\\texttt{Typewriter family (monospace)}\n\n% Series (weight/width)\n\\textmd{Medium series (normal)}\n\\textbf{Bold series}\n\n% Shape (slant/style)\n\\textup{Upright shape}\n\\textit{Italic shape}\n\\textsl{Slanted shape}\n\\textsc{Small Caps Shape}\n\n\\end{document}"} />

<RenderedOutput title="Rendered output" ctaHref="https://app.latex-cloud-studio.com/?utm_source=resources&utm_medium=rendered_output&utm_campaign=docs_open_app&utm_content=learn_latex_fonts">
  <LatexPreview src="/images/rendered/learn-latex-fonts-01/page-1.svg" alt="Compiled PDF page 1 from font-attributes.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

### Combining Font Attributes

<LatexSource filename="combining-fonts.tex" source={"% All combinations work\n\\textsf{\\textbf{Sans serif bold}}\n\\texttt{\\textit{Typewriter italic}}\n\\textrm{\\textbf{\\textit{Roman bold italic}}}\n\\textsc{\\textbf{Bold Small Caps}}\n\n% Using declarations\n{\\sffamily\\bfseries\\itshape Sans serif bold italic}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-fonts-02/page-1.svg" alt="Compiled PDF page 1 from combining-fonts.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
</RenderedOutput>

## Font Packages (pdfLaTeX)

### Popular Font Packages

<LatexSource filename="font-packages.tex" source={"\\documentclass{article}\n\n% Choose one matching text-and-math family per document.\n\\usepackage{lmodern}\n\n% Alternatives (activate one pair instead of lmodern):\n% \\usepackage{newtxtext,newtxmath} % Times-like\n% \\usepackage{newpxtext,newpxmath} % Palatino-like\n% \\usepackage{libertine}           % Linux Libertine\n\n\\begin{document}\nLatin Modern text with matching mathematics: $E = mc^2$.\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-fonts-03/page-1.svg" alt="Compiled PDF page 1 from font-packages.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

### Font Package Comparison

| Package     | Style     | Math Support | Use Case            |
| ----------- | --------- | ------------ | ------------------- |
| `lmodern`   | Modern    | Yes          | Default improvement |
| `mathptmx`  | Times     | Yes          | Traditional papers  |
| `helvet`    | Helvetica | No           | Modern look         |
| `mathpazo`  | Palatino  | Yes          | Books, elegant      |
| `libertine` | Libertine | Yes          | Professional        |
| `fourier`   | Utopia    | Yes          | Technical docs      |

## System Fonts (XeLaTeX/LuaLaTeX)

### Using System Fonts

<LatexSource filename="system-fonts.tex" source={"\\documentclass{article}\n\\usepackage{fontspec}\n\n% Portable fonts installed in the LaTeXCloud compiler image\n\\setmainfont[\n  Ligatures=TeX,\n  Numbers=OldStyle,\n  Scale=1.0\n]{Times New Roman}\n\\setsansfont{Arial}\n\\setmonofont{Courier New}\n\n\\begin{document}\nThis document uses a system serif font directly.\\\\\n{\\sffamily This line uses the configured sans-serif font.}\\\\\n{\\ttfamily This line uses the configured monospaced font.}\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-fonts-04/page-1.svg" alt="Compiled PDF page 1 from system-fonts.tex" caption="Generated from the shown source with XeLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.28} height={841.89} />
</RenderedOutput>

### Font Selection by Name

<LatexSource filename="font-by-name.tex" source={"\\documentclass{article}\n\\usepackage{fontspec}\n\n% Define custom font commands\n\\newfontfamily\\headingfont{Arial}\n\\newfontfamily\\specialfont{Times New Roman}\n\\newfontfamily\\codefont{Courier New}\n\n\\begin{document}\n\n{\\headingfont\\Large This is a heading in Arial}\n\nRegular text in the main font.\n\n{\\specialfont\\itshape Special serif text}\n\n{\\codefont\\small Code examples in Courier New}\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-fonts-05/page-1.svg" alt="Compiled PDF page 1 from font-by-name.tex" caption="Generated from the shown source with XeLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.28} height={841.89} />
</RenderedOutput>

## Font Features

### OpenType Features (XeLaTeX/LuaLaTeX)

<LatexSource filename="opentype-features.tex" source={"\\documentclass{article}\n\\usepackage{fontspec}\n\n\\setmainfont{Times New Roman}[\n  Ligatures=TeX,\n  Numbers=OldStyle\n]\n\n% Specific features\n\\newfontfamily\\displayfont{Times New Roman}[\n  Numbers={Proportional,OldStyle},\n  Ligatures=TeX\n]\n\n\\begin{document}\n\n% Ligatures\nOffice, shelf, affiliate (fi, fl, ffi ligatures)\n\n% Old style numbers\nRegular: 0123456789 vs {\\addfontfeatures{Numbers=OldStyle}0123456789}\n\n% Small caps require a font family that provides small-cap glyphs.\n% {\\scshape Small Capitals Text}\n\n% A separately configured display face\n{\\displayfont Display text with proportional old-style numbers: 0123456789}\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-fonts-06/page-1.svg" alt="Compiled PDF page 1 from opentype-features.tex" caption="Generated from the shown source with XeLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.28} height={841.89} />
</RenderedOutput>

### Microtype Package

<LatexSource filename="microtype.tex" source={"\\documentclass{article}\n% Full features (pdfLaTeX)\n\\usepackage[\n  protrusion=true,\n  expansion=true,\n  tracking=true,\n  kerning=true,\n  spacing=true\n]{microtype}\n\n% Fine-tuning\n\\microtypesetup{\n  protrusion={true,alltext},\n  expansion={true,alltext,compat}\n}\n\n\\begin{document}\nMicrotype improves typography through:\n\\begin{itemize}\n\\item Character protrusion (margin kerning)\n\\item Font expansion (better justification)\n\\item Tracking (letter spacing)\n\\item Additional kerning\n\\end{itemize}\n\nThe improvements are subtle but create more professional results.\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-fonts-07/page-1.svg" alt="Compiled PDF page 1 from microtype.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

## Font Sizes

### Changing Font Size

<LatexSource filename="font-sizes.tex" source={"\\documentclass[12pt]{article}  % Base size: 10pt, 11pt, or 12pt\n\n% Exact sizes\n\\fontsize{14}{17}\\selectfont  % 14pt font, 17pt baseline\nThis text is exactly 14 points.\n\n% Relative sizes\n{\\tiny Tiny text (5pt at 10pt base)}\n{\\small Small text (9pt at 10pt base)}\n{\\large Large text (12pt at 10pt base)}\n{\\Huge Huge text (25pt at 10pt base)}\n\n% Custom size commands\n\\newcommand{\\customsize}{\\fontsize{13}{16}\\selectfont}\n{\\customsize Custom 13pt text}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This declaration configures the document class and its options. It does not create visible page content by itself, so no PDF preview is claimed.
  </Info>
</RenderedOutput>

### Size Commands Reference

| Command         | 10pt Article | 11pt Article | 12pt Article |
| --------------- | ------------ | ------------ | ------------ |
| `\tiny`         | 5pt          | 6pt          | 6pt          |
| `\scriptsize`   | 7pt          | 8pt          | 8pt          |
| `\footnotesize` | 8pt          | 9pt          | 10pt         |
| `\small`        | 9pt          | 10pt         | 10.95pt      |
| `\normalsize`   | 10pt         | 10.95pt      | 12pt         |
| `\large`        | 12pt         | 12pt         | 14.4pt       |
| `\Large`        | 14.4pt       | 14.4pt       | 17.28pt      |
| `\LARGE`        | 17.28pt      | 17.28pt      | 20.74pt      |
| `\huge`         | 20.74pt      | 20.74pt      | 24.88pt      |
| `\Huge`         | 24.88pt      | 24.88pt      | 24.88pt      |

## Mathematical Fonts

### Math Font Packages

<LatexSource filename="math-fonts.tex" source={"% Load one matching text-and-math family.\n\\usepackage{lmodern}\n\n% Alternatives (activate one family instead):\n% \\usepackage{newtxtext,newtxmath}\n% \\usepackage{newpxtext,newpxmath}\n\n% Math alphabets\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n\\usepackage{mathrsfs}     % \\mathscr\n\n% Usage\n$\\mathbb{R}$, $\\mathcal{A}$, $\\mathscr{L}$, $\\mathfrak{g}$"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-fonts-09/page-1.svg" alt="Compiled PDF page 1 from math-fonts.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
</RenderedOutput>

### Unicode Math (XeLaTeX/LuaLaTeX)

<LatexSource filename="unicode-math.tex" source={"\\documentclass{article}\n\\usepackage{unicode-math}\n\n% Select a TeX-distributed OpenType math font by its portable file name.\n\\setmathfont{latinmodern-math.otf}\n\n% Alternative:\n% \\setmathfont{texgyretermes-math.otf}\n\n\\begin{document}\nUnicode math allows: $α + β = γ$ and $∫_0^∞ e^{-x²} dx = \\frac{√π}{2}$\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-fonts-10/page-1.svg" alt="Compiled PDF page 1 from unicode-math.tex" caption="Generated from the shown source with XeLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.28} height={841.89} />
</RenderedOutput>

## Special Typography

### Drop Caps

<LatexSource filename="drop-caps.tex" source={"\\documentclass{article}\n\\usepackage{lettrine}\n\\begin{document}\n\n\\lettrine[lines=3]{O}{nce upon a time}, in a land far away, \nthere lived a typographer who loved beautiful drop caps. \nThis elegant initial letter adds a classic touch to the \nbeginning of chapters or sections.\n\n\\lettrine[lines=2,loversize=0.1]{T}{his} is a smaller drop cap.\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-fonts-11/page-1.svg" alt="Compiled PDF page 1 from drop-caps.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

### Custom Fonts for Special Text

<LatexSource filename="special-fonts.tex" source={"\\documentclass{article}\n\\usepackage{fontspec}  % XeLaTeX/LuaLaTeX\n\n% Define special purpose fonts\n\\newfontfamily\\chapterfont{Arial}\n\\newfontfamily\\quotefont{Times New Roman}[Scale=1.1]\n\\newfontfamily\\symbolfont{Arial}\n\n\\begin{document}\n\n{\\chapterfont\\Huge Chapter One}\n\n{\\quotefont\\itshape \"Beautiful typography is invisible, \nyet it shapes how we perceive the written word.\"}\n\n{\\symbolfont ★ ♫ ✦}  % Portable Unicode symbols\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-fonts-12/page-1.svg" alt="Compiled PDF page 1 from special-fonts.tex" caption="Generated from the shown source with XeLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.28} height={841.89} />
</RenderedOutput>

## Font Troubleshooting

### Common Issues and Solutions

<LatexSource filename="font-fixes.tex" source={"% Font not found (XeLaTeX/LuaLaTeX)\n\\setmainfont{Arial}[\n  Extension = .ttf,\n  Path = /path/to/fonts/,\n  UprightFont = *-Regular,\n  BoldFont = *-Bold,\n  ItalicFont = *-Italic\n]\n\n% Missing characters\n\\usepackage{textcomp}  % Additional symbols\n\\usepackage[T1]{fontenc}  % Better encoding\n\n% Font substitution warnings\n\\usepackage{silence}\n\\WarningFilter{latexfont}{Font shape}\n\n% Check available fonts (XeLaTeX/LuaLaTeX)\n% Run in terminal: fc-list : family"} />

<RenderedOutput title="Compiler result">
  <Warning>
    This example is intentionally invalid. The automated example test verifies that compilation fails with: `cannot be found`.
  </Warning>
</RenderedOutput>

## How to Set the Document Font to Times New Roman

Times New Roman itself is a proprietary Microsoft font, so what you normally want is
a metric-compatible equivalent that ships with TeX.

With pdfLaTeX, load one package in the preamble and everything follows:

* `\usepackage{newtxtext,newtxmath}` — the current recommendation, Times for text
  and matching maths
* `\usepackage{mathptmx}` — older, still widely used, Times text and maths
* `\usepackage{times}` — obsolete, leaves maths in Computer Modern; avoid it

With XeLaTeX or LuaLaTeX you can use the real system font directly through
`fontspec`: `\setmainfont{Times New Roman}`, provided the font is installed. On a
Linux build machine it usually is not, in which case `\setmainfont{TeX Gyre Termes}`
gives you the same metrics.

Journals that ask for "Times New Roman 12pt" accept any of the metric-compatible
options above.

## Best Practices

<Tip>
  **Font guidelines:**

  1. **Consistency**: Use maximum 2-3 font families per document
  2. **Readability**: Test fonts at actual reading size
  3. **Purpose**: Match font to document type (serif for print, sans for screen)
  4. **Licensing**: Ensure fonts are properly licensed
  5. **Fallbacks**: Provide alternatives for missing fonts
  6. **Testing**: Check output on different systems/viewers
</Tip>

## Font Comparison

<CardGroup cols={2}>
  <Card title="For Traditional Documents" icon="file-alt">
    * Times (mathptmx)
    * Palatino (mathpazo)
    * Computer Modern (default)
    * Latin Modern (lmodern)
  </Card>

  <Card title="For Modern Documents" icon="laptop">
    * Helvetica (helvet)
    * Open Sans
    * Source Sans Pro
    * Roboto
  </Card>

  <Card title="For Technical Documents" icon="cog">
    * Computer Modern
    * STIX Two
    * Libertinus
    * KP Fonts
  </Card>

  <Card title="For Books" icon="book">
    * Minion Pro
    * Sabon
    * Garamond
    * Baskerville
  </Card>
</CardGroup>

## Quick Reference

| Task         | pdfLaTeX                                    | XeLaTeX/LuaLaTeX                  |
| ------------ | ------------------------------------------- | --------------------------------- |
| Times font   | `\usepackage{mathptmx}`                     | `\setmainfont{Times New Roman}`   |
| Sans default | `\renewcommand{\familydefault}{\sfdefault}` | `\setmainfont{Arial}`             |
| Math fonts   | `\usepackage{newtxmath}`                    | `\usepackage{unicode-math}`       |
| Custom font  | Use packages                                | `\newfontfamily\myfont{FontName}` |

***

<Info>
  **Next**: Learn about [Mathematical equations](/learn/latex/mathematics/equations) to create complex mathematical expressions with proper formatting.
</Info>
