Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiline text to fit parent container in React JS

I am using a flexbox layout and am trying to get the text in a specific div to be resized to fit that div.

So for example, if I have code as follows:

<div style={{display: "flex"}}>
   <div style={{flex: 1}}>
      A really, really, really, really long phrase here that will fit this div, and may wrap onto multiple lines if necessary. In this case it should fill half of the available space as the other div will cover the other half of the space.
   </div>
   <div style={{flex: 1}}>
      Some other text
   </div>
</div>

In reality, the text will be pulled from a database, so will be dynamic in length.

How can I get the text in the first div to automatically adjust to fit the entire div?

Clarification: the div should stay a fixed size and only the text should be downsized to fit the div rather than overflowing the div.

Update

I have also posted a more specific question about a specific module called react-textfit not working the way I would expect it to work.

like image 381
kojow7 Avatar asked May 25 '19 03:05

kojow7


2 Answers

Here is some code that should do what you are asking.

let size_div = document.querySelector("#font_size");
let div = document.querySelector("#fixed");

while (div.scrollHeight > div.clientHeight) {
  let style = window.getComputedStyle(div, null).getPropertyValue('font-size');
  let fontSize = parseFloat(style);

  if (fontSize <= 1) {
    break;
  }

  div.style.fontSize = "" + (fontSize - 1) + "px";
  size_div.innerHTML = "&nbsp;" + div.style.fontSize;
}

enter image description here enter image description here

You can try it out here: https://codepen.io/lowtex/pen/xNawEO

like image 113
lowtex Avatar answered Sep 19 '22 12:09

lowtex


You could simply hard code the size to 50 %

<div style="display:flex">
  <div style="width:50%;background:lightgrey;">
    A really, really, really, really long phrase here that will fit this div, and may wrap onto multiple lines if necessary. In this case it should fill half of the available space as the other div will cover the other half of the space.
  </div>
  <div style="width:50%;background:lightblue;">
    Some other text
  </div>
</div>

enter image description here

like image 21
Ji aSH Avatar answered Sep 19 '22 12:09

Ji aSH