Milind Daraniya

Responsive Text with Respect to Container Width

Published February 23rd, 2023 12 min read

Responsive text is essential for ensuring that text elements on a webpage adjust proportionally to the width of their container. By making text responsive, you can improve the readability and user experience on various devices with different screen sizes. In this post, we'll explore techniques for creating responsive text that dynamically adjusts its size based on the container width.

Using vw Units

One straightforward method for creating responsive text is by using the viewport width (vw) unit. The vw unit represents a percentage of the viewport's width, and it allows the text to scale with the container's width.

<style>
  .responsive-text {
    font-size: 4vw; /* Adjust the font size as per your requirement */
  }
</style>

<div class="responsive-text">
  This text will adjust its size based on the container width.
</div>

Using calc and Media Queries

Another approach involves using the calc function with media queries to set different font sizes based on the container width breakpoints.

<style>
  .responsive-text {
    font-size: calc(12px + 2vw); /* Adjust the base font size and vw factor as needed */
  }

  @media (min-width: 768px) {
    .responsive-text {
      font-size: calc(16px + 1.5vw);
    }
  }

  @media (min-width: 1200px) {
    .responsive-text {
      font-size: 18px; /* Set a fixed font size for larger screens */
    }
  }
</style>

<div class="responsive-text">
  This text will adjust its size based on the container width and media queries.
</div>

Fluid Typography with clamp

Using the clamp function is another effective way to create fluid typography that adjusts to the container width while ensuring a minimum and maximum font size.

<style>
  .responsive-text {
    font-size: clamp(14px, 5vw, 30px); /* Set the minimum, preferred, and maximum font sizes */
  }
</style>

<div class="responsive-text">
  This text will have fluid typography with respect to the container width.
</div>

Creating responsive text that adjusts proportionally to the container width is crucial for improving the user experience across different devices and screen sizes. By using vw units, calc with media queries, or the clamp function, you can achieve fluid typography that adapts dynamically based on the available space.