Mike
Mike

Reputation: 65

Making a Div fit its content

I'm trying to force a div to fit the text inside. No matter what I have tried, there seems to be extra white space. Here is my code:

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>

Upvotes: 2

Views: 3720

Answers (2)

Văn Quyết
Văn Quyết

Reputation: 2538

div { width: max-content; }

Support browsers: https://caniuse.com/#search=max-content

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

Or you can use this way (change display attribute):

div { display: table; }

Upvotes: 2

Saurav Rastogi
Saurav Rastogi

Reputation: 9731

Use word-break: break-all, like:

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

Have a look at the snippet below:

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>

Hope this helps!

Upvotes: 3

Related Questions