CSS

line-height


The line-height property in CSS controls the space between lines of text. Adjusting line-height can make your text more readable and visually appealing. Here’s how you can use it.

 

Basic Usage

The line-height property can be set in several ways: using a number, a length (like pixels or ems), or a percentage. Here are some examples:

 

Using a Number

When you use a number, it's a unitless value that is multiplied by the element’s font size to get the line height.

Example:

p {
  line-height: 1.5;
}

If the font size is 16px, the line height will be 16px * 1.5 = 24px.

Using a Length

You can also specify line-height using length values like pixels (px) or ems (em).

Example:

p {
  line-height: 24px;
}

Using a Percentage

Using a percentage sets the line height relative to the font size.

Example:

p {
  line-height: 150%;
}

If the font size is 16px, the line height will be 16px * 1.5 = 24px.

 

Example

body {
  font-family: Arial, sans-serif;
}

p {
  font-size: 16px;
  line-height: 1.6; /* or you can use 24px or 150% */
}

This will ensure that your paragraphs have enough space between lines, making them easier to read.

 

Adjusting Line-Height for Different Elements

You might want different line heights for different text elements. For instance, headings might need a tighter line height than body text.

Example:

h1 {
  font-size: 32px;
  line-height: 1.2;
}

p {
  font-size: 16px;
  line-height: 1.6;
}

This way, your headings will be more compact while your paragraphs remain easily readable.

 

Practical Example 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CoderSmile Example</title>
</head>
<body>
    <h1>Welcome to CoderSmile</h1>
    <h2>Getting Started</h2>
    <p>This guide will help you set up your development environment quickly and easily. Follow the steps below to get started.</p>
    <p>Whether you are a beginner or an experienced developer, having the right tools is crucial for efficient coding.</p>
</body>
</html>
<style>
/* styles.css */
body {
  font-family: Arial, sans-serif;
  margin: 20px;
}

h1 {
  font-size: 32px;
  line-height: 1.3;
}

h2 {
  font-size: 24px;
  line-height: 1.4;
}

p {
  font-size: 16px;
  line-height: 1.6;
}

</style>