Multiline text to fit parent container in React JS

前端 未结 4 2220
情歌与酒
情歌与酒 2021-02-19 19:51

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:

&l         


        
相关标签:
4条回答
  • 2021-02-19 20:24

    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;
    }
    

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

    0 讨论(0)
  • 2021-02-19 20:24
    <div style={{ display: "flex" }}>
    <div
        style={{
        flex: 1,
        backgroundColor: "lightGrey",
        wordBreak: "break-word"
        }}
    >
        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, backgroundColor: "lightBlue" }}>
        Some other text
    </div>
    </div>
    
    0 讨论(0)
  • 2021-02-19 20:33

    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>
    

    0 讨论(0)
  • 2021-02-19 20:43

    I am not a reactJs user but I have worked with CSS flex

    you can set height of the container to auto so that it changes as we get the content. Also, you should set min-height and max-height properties in css so that if content is less that given length, it appears on min-height and if the content is way to big, it does not exceed the given container height.

    In order to disallow content from getting out of the box, you can use overflow:hidden. this will keep the content from getting out of the box.

    Hope this gives some help with how you want to proceed.

    0 讨论(0)
提交回复
热议问题