使Div符合其内容

时间:2017-10-30 04:24:49

标签: html css

我试图强制div来适应里面的文字。无论我尝试过什么,似乎都有额外的空白区域。这是我的代码:



body {
  background-color: #000;
}

.holding {
  width: 500px;
  background-color: red;
  height: 500px;
  padding: 40px 100px;
  max-width: 400px;
  width: fit-content;
}

.childone {
  background-color: white;
  display: inline;
  padding: 20px;
  float: left;
  clear: both;
}

.clear {
  clear: both;
}

.childtwo {
  background-color: white;
  display: inline-block;
  float: left;
  padding: 10px;
}

<body>

  <div class="holding">
    <div class="childone">This is the Title and I really the div to end here with.no.extra.white.space </div>
    <div class="clear"></div>
    <div class="childtwo">This is the next child div with a bund of stuff.</div>
  </div>

</body>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:3)

使用 word-break: break-all ,例如:

.childone {
  word-break: break-all;
}

请看下面的代码段:

body {
  background-color: #000;
}

.holding {
  width: 500px;
  background-color: red;
  height: 500px;
  padding: 40px 100px;
  max-width: 400px;
  width: fit-content;
}

.childone {
  background-color: white;
  display: inline;
  padding: 20px;
  float: left;
  clear: both;
  word-break: break-all;
}

.clear {
  clear: both;
}

.childtwo {
  background-color: white;
  display: inline-block;
  float: left;
  padding: 10px;
}
<body>

  <div class="holding">
    <div class="childone">This is the Title and I really the div to end here with.no.extra.white.space </div>
    <div class="clear"></div>
    <div class="childtwo">This is the next child div with a bund of stuff.</div>
  </div>

</body>

希望这有帮助!

答案 1 :(得分:1)

div { width: max-content; }

支持浏览器:https://caniuse.com/#search=max-content

参考:https://developer.mozilla.org/en-US/docs/Web/CSS/max-width

或者您可以使用这种方式(更改display属性):

div { display: table; }

答案 2 :(得分:0)

填充填充:1px;这将解决您的问题。see the pic

.childone {

填充:1px;

}

.childtwo {

填充:1px; }