CSS FONT-SIZE

AKASH E



CSS Font-size

The font-size property in CSS sets the size of the text in an element. By default, it is set to "medium." You can use different values like "xx-small," "small," or "x-small" to adjust the text size. This property can be used with any HTML element.

Syntax

font-size: medium/large/x-large/xx-large/xx-small/x-small/small;
The font-size can be relative or absolute.

Absolute-size

It sets the text to a specific size. However, using absolute sizes may not work consistently across all browsers. This approach is useful when you know the exact physical size of the display.

Relative-size

It adjusts the text size based on the size of surrounding elements. Using relative sizes allows the text size to be adjusted more consistently across different browsers.

Font-size With pixels

Setting the text size in pixels gives you complete control over how big the text appears.

Example

<!DOCTYPE html>
<html>
<head>
<style>
 #first {
   font-size: 41px;
}
#second {
  font-size: 22px;
}
</style>
</head>
<body>
<p id="first">This paragraph has a font size of 40px.</p>
<p id="second">This paragraph has a font size of 20px.</p>
</body>
</html>

Font-size With em

It is used to adjust the text size. Many developers prefer using em units over pixels. The World Wide Web Consortium (W3C) recommends this approach. By default, browsers use a text size of 16px, so 1em equals 16px.
To convert pixels to em, use the formula: em = pixels / 16.

Example

<!DOCTYPE html>
<html>
<head>
<style>
 #first {
   font-size: 2.5em; /* 40px / 16 = 2.5em */
}
 #second {
   font-size: 1.875em; /* 30px / 16 = 1.875em */
}
 #third {
   font-size: 0.875em; /* 14px / 16 = 0.875em */
}
</style>
</head>
<body>
<p id="first">First paragraph.</p>
<p id="second">Second paragraph.</p>
<p id="third">Third paragraph.</p>
</body>
</html>

Responsive Font-size

You can set the text size using the vw unit, which stands for 'viewport width'. The viewport is the width of the browser window.
1vw equals 1% of the viewport width.
So, if the viewport width is 50 cm, then 1vw is equal to 0.5 cm.

Example

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<p style="font-size: 5vw;">First paragraph with a font size of 5vw.</p>
<p style="font-size: 10vw;">Second paragraph with a font size of 10vw.</p>
</body>
</html>

Font-size With the length property

It sets the font size using length units such as cm, px, or pt. Negative values are not allowed for the font-size property.

Syntax

font-size:length;

Example

<!DOCTYPE html>
<html>
<head>
<style>
.length {
  color: red;
  font-size: 5cm;
}
</style>
</head>
<body>
<h1>Font Size Property</h1>
<p class="length">A paragraph with a font size of 5cm.</p>
</body>
</html>


Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send