Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Shorthand property to set the font with CSS
The CSS font property is a shorthand that allows you to set multiple font-related properties in a single declaration, including font style, variant, weight, size, line-height, and family.
Syntax
font: [font-style] [font-variant] [font-weight] font-size[/line-height] font-family;
The font-size and font-family values are required, while other properties are optional.
Example
Here's how to use the font shorthand property to apply multiple font styles at once:
<html>
<head>
<style>
.shorthand-example {
font: italic small-caps bold 16px/1.5 Georgia, serif;
margin: 10px 0;
padding: 10px;
border: 1px solid #ccc;
}
.individual-properties {
font-style: italic;
font-variant: small-caps;
font-weight: bold;
font-size: 16px;
line-height: 1.5;
font-family: Georgia, serif;
margin: 10px 0;
padding: 10px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<h3>Using Font Shorthand:</h3>
<p class="shorthand-example">
This text uses the font shorthand property.
</p>
<h3>Using Individual Properties:</h3>
<p class="individual-properties">
This text uses individual font properties (same result).
</p>
</body>
</html>
Font Property Order
The font shorthand follows a specific order. Here's the breakdown:
<html>
<head>
<style>
.example1 { font: 14px Arial; }
.example2 { font: bold 18px Helvetica; }
.example3 { font: italic normal 600 20px/1.4 "Times New Roman"; }
</style>
</head>
<body>
<p class="example1">Minimum required: size and family</p>
<p class="example2">With weight: bold 18px Helvetica</p>
<p class="example3">Full syntax: italic normal 600 20px/1.4 "Times New Roman"</p>
</body>
</html>
Comparison
| Approach | Code Length | Readability | Maintainability |
|---|---|---|---|
| Font Shorthand | Shorter | Compact | Quick updates |
| Individual Properties | Longer | More explicit | Easier to modify specific values |
Common Use Cases
<html>
<head>
<style>
.heading { font: bold 24px/1.2 Arial, sans-serif; }
.body-text { font: normal 16px/1.6 Georgia, serif; }
.caption { font: italic 12px Helvetica, sans-serif; }
</style>
</head>
<body>
<h2 class="heading">Main Heading</h2>
<p class="body-text">This is the main body text with readable line height.</p>
<p class="caption">Image caption with smaller italic text.</p>
</body>
</html>
Conclusion
The CSS font shorthand property provides an efficient way to set multiple font properties at once. Use it when you need to define several font characteristics together, but consider individual properties when you only need to modify specific values.
Advertisements
