CSS - font-size property

What is font-size in CSS ?

font-size in CSS is a property that defines the length (size) of a font.

font-size by himself is an element of typography.

By setting font-size on different media query, you will set up what's called a responsive typography

Example

Fix amount

The font-size uses generally a relative sizing

body {
  font-size: 16px;
}
p.base1 { font-size: 1rem } /* ie 1rem = 1 * 16px = 12 px */
p.base2 { font-size: 2rem } /* ie 2rem = 2 * 16px = 32 px */
  • The html code
<p class="base1">16px text</p>
<p class="base2">32px text</p>
  • Output:

Based on the width of the viewport

The following sets the font-size so that exactly 40em fits within the viewport, ensuring that roughly the same amount of text always fills the screen no matter the screen size.

With the root selector, the calc function and the vw length unit (1/100th of the window's width)

:root {
  font-size: calc(100vw / 40);
}

Size

Base

The base unit size for relative sizing that is set on the body has generally a set of 16px

This is the default for web browsers which means that setting a 1rem on the body will get you a font-size of 16px.

body {
    font-size: 1rem;
}

How to

Calculated font-size

Window/getComputedStyle

.parent { font-size: 20px }
.medium { font-size: 0.75em }
.small { font-size: 0.5em }
<div class="parent">
    <p>Hello Nico</p>
    <p class="medium">Hello Nico</p>
    <p class="small">Hello Nico</p>
</div>
div = document.querySelector("div");
console.log("The font size of the parent div element is "+window.getComputedStyle(div).fontSize);
allP = document.querySelectorAll("p");
console.log("The font size of the first p element is "+window.getComputedStyle(allP.item(0)).fontSize);
console.log("The font size of the medium p element is "+window.getComputedStyle(allP.item(1)).fontSize);
console.log("The font size of the small p element is "+window.getComputedStyle(allP.item(2)).fontSize);

Readability

The higher the font-size, the readable.

Not that for small size, you can use the font-size-adjust property 1) legibility of fonts, especially at small sizes


Powered by ComboStrap