Unable to create an HTML Div Element that Fits to the text size

前端 未结 2 1347
青春惊慌失措
青春惊慌失措 2021-01-22 16:30

I\'m unable to get a div to fit the size of the text inside of it.

I have 2 divs, and I want the inner div to:

1. Fit inside the outer div.

相关标签:
2条回答
  • 2021-01-22 17:05

    Your issue is happening because of the long word with no-spaces so the browser cannot break it and it's not fitting with the rest of line so it's going to the new line leaving a big space behind.

    to solve this issue you can use this css

    .divForText{
      ...
      hyphens: auto;
      ...
    }
    
    

    the browser will add a hyphen automatically when it's needed.

    .wrapper{
      border: 1px solid blue;
      text-align: center;
      overflow: hidden;
      padding: 25px;
      margin: auto;
      width: 50%;
    }
    
    .divForText{
      border: 1px solid black;
      display: inline-block;
      text-align: left;
      padding: 15px;
      hyphens: auto;
    }
    <div class="wrapper">
    <div class="divForText">
    Text... Text... Text... Text... Text... Text... VeryLongWordToCheckTheGapProblemOnLeftAndRightSides Text...  Text...
    </div>
    </div>

    0 讨论(0)
  • 2021-01-22 17:14

    you could use word-break:break all; so your corrected css will be as follow:

    .divForText{
      border: 1px solid black;
      display: inline-block;
      text-align: left;
      padding: 15px;
      word-break: break-all;
    
    }
    

    or

    .divForText{
      border: 1px solid black;
      display: inline-block;
      text-align: left;
      padding: 15px;
      word-break: break-word;
    
    }
    

    don't forget to mark as answered if it works for you, as for others could help them.

    or

    use overflow-x:hidden; that should wrap the text in a decent way, with css there is a lot of ways you can wrap your long text, here is also a useful link here is a useful link

    .divForText{
      border: 1px solid black;
      display: inline-block;
      text-align: left;
      padding: 15px;
      overflow-x: hidden;
      word-wrap: break-word;  
    }
    
    0 讨论(0)
提交回复
热议问题