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

我怕爱的太早我们不能终老 提交于 2020-01-21 23:54:47

问题


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. Be centered inside the wrapping div.

The problem I am experiencing is that when I play around with the width of the view, I am getting a large unwanted gap between the text and the div's border, as you can see here:

How can I prevent this gap, and furthermore; how can I make the div center inside the large div to make its size big enough to fit the text inside of it?

Here is my fiddle test: https://jsfiddle.net/gv1xLd8s

My HTML code:

<div class="wrapper">
<div class="divForText">
Text... Text... Text... Text... Text... Text... 
VeryLongWordToCheckTheGapProblemOnLeftAndRightSides
Text...  Text...
</div>
</div>

My CSS code:

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

Thanks!

(Note: I want to accomplish this using pure HTML and CSS)


回答1:


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



回答2:


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>


来源:https://stackoverflow.com/questions/59557367/unable-to-create-an-html-div-element-that-fits-to-the-text-size

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!