In web design, it is important to be able to manage the text size. It is not advisable to adjust font size in such a way that paragraphs look like headings, or headings look like paragraphs. Fonts should be sized according to their purpose. Headings should be larger than body text, while subheadings should be smaller than headings but larger than body text. This ensures readability and clarity.
Text Alignment
In CSS by default, the text elements are aligned to the left of their container. We can use the text-align property to change the alignment of text within an element. There are four different values of text alignment:
center: center the text
left: align the text to the left of its container
right: align the text to the right of its container
justify: the text will spread out to fill out the full width of its container
Text sizing
Changing the default size of text elements will be necessary in many cases. Using the font-size property, you can change the size of your text. Px is the most common absolute value, while ems and rems are the most common relative values.
Set Font Size With Pixels
Absolute size sets the text to a specified size and is useful when the physical size of the output is known. The default text size in browsers is 16px.
<html>
<head> Font size
</head>
<body>
<h1>Heading</h1>
<h2>Heading 2</h2>
<p>You can do amazing things with code</p>
</body>
</html>
h1 {
font-size: 60px;
}
h2 {
font-size: 40px;
}
p {
font-size: 30px;
}
Set Font Size With em
Relative size sets the size relative to surrounding elements. This allows us to resize the text in the browser. The default size of 1em is 16px.
The size can be calculated from pixels to em using this formula: pixels/16=em.
<html>
<head> Font size
</head>
<body>
<div class = "relative">
<span>outer
<span>inner</span>
</span>
</div>
</body>
</html>
.relative{
font-size: 100%;
}
span {
font-size: 2.0em;
}
In the above example, the default font-size of “outer” word is 16px and the font-size of “inner” word is 2.0em more than the “outer” word. This is because the “inner” <span>’s font-size is relative to its parent’s font-size. This is called as compounding.
Spacing text
We use the line-height property to set the height of a line of text.
<html>
<head> Font size
</head>
<body>
<h1>Heading</h1>
<h2>Heading 2</h2>
<p>You can do amazing things with code</p>
</body>
</html>
h1 {
font-size: 60px;
line-height: 10px;
}
h2 {
font-size: 40px;
line-height: 5px;
}
p {
font-size: 30px;
line-height : 5px;
}