CSS

font-size


The font-size property in CSS is used to specify the size of the font. It can take various values including absolute, relative, length, percentage, and keyword values. Here’s a detailed explanation of how to use the font-size property:

Absolute-size Keywords

These keywords are predefined and adjust the font size to a specific value:

  • xx-small
  • x-small
  • small
  • medium (default)
  • large
  • x-large
  • xx-large
p {
    font-size: large;
}

 

Relative-size Keywords

These adjust the font size relative to the parent element's font size:

  • larger
  • smaller
p {
    font-size: larger;
}

 

Length Units

These allow you to specify the font size with specific measurements such as pixels, ems, rems, and more:

  • px (pixels): A specific number of pixels.
p {
    font-size: 16px;
}
  • em: Relative to the font size of the element itself.
p {
    font-size: 1.5em; /* 1.5 times the size of the parent element's font size */
}
  • rem: Relative to the font size of the root element (usually <html>).
p {
    font-size: 1rem; /* 1 times the size of the root element's font size */
}
  • %: A percentage of the parent element's font size.
p {
    font-size: 150%; /* 150% of the parent element's font size */
}
  • vw (viewport width) and vh (viewport height): A percentage of the viewport's width or height.
p {
    font-size: 2vw; /* 2% of the viewport's width */
}

 

Example Usage

Here’s how you might use different values for font-size in your CSS:

body {
    font-size: 16px; /* Base font size */
}

h1 {
    font-size: 2em; /* 2 times the base font size */
}

h2 {
    font-size: 1.5rem; /* 1.5 times the root element's font size */
}

p {
    font-size: 100%; /* 100% of the parent element's font size */
}

small {
    font-size: smaller; /* Smaller than the parent element's font size */
}

 

Responsive Font Sizes

You can use media queries to make your font sizes responsive:

body {
    font-size: 16px;
}

@media (max-width: 600px) {
    body {
        font-size: 14px;
    }
}

@media (min-width: 1200px) {
    body {
        font-size: 18px;
    }
}

 

Using CSS Variables for Font Sizes

CSS variables can make managing font sizes easier:

:root {
    --base-font-size: 16px;
    --large-font-size: 2rem;
}

body {
    font-size: var(--base-font-size);
}

h1 {
    font-size: var(--large-font-size);
}

By understanding and utilizing the various options for font-size in CSS, you can create more flexible, readable, and responsive web designs.