Scipion
Scipion

Reputation: 11888

Css h1 matching div width

I have the following html:

<!DOCTYPE html>
<html>
  <body>
    <h1 style="margin-bottom: 0;">Hello Plunker!</h1>
    <div style="background-color: red; height: 100px; width: 250px;"></div>
  </body>
</html>

Basically I would like to give my h1 a width that the text inside it should occupy no matter if I add or remove a word (adapting the font-size and the letter-spacing according to it). I could change my "Hello Plunker" and the last letter should still finish where the div below finishes.

I can use some js if needed but not Jquery

Upvotes: 1

Views: 2177

Answers (3)

Adam K.
Adam K.

Reputation: 912

Just an Idea of using transform:scale(jQueryCalc) - to make content fit its parents innerWidth.

$(document).ready(function() {
  $(".fit").each(function() {
    $(this).css("transform", "scale(" + ($(this).parent().innerWidth() / $(this).width()) + ")");
  });
});
.container {
  background-color: red;
  height: 70px;
  width: 250px;
  display: inline-block;
  position: relative;
  overflow: hidden;
}

.fit{
  display: block;
  color: #FFF;
  float: left;
  transform-origin: left top;
  white-space: nowrap;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <h1 class="fit">Hello Plunker!</h1>
</div>
<div class="container">
  <span class="fit">Well this should work</span>
</div>
<div class="container">
  <span class="fit">Well this should work; Well this should work</span>
</div>
<div class="container">
  <span class="fit">Well this should work; Well this should work; Well this should work; Well this should work</span>
</div>

Upvotes: 0

domsson
domsson

Reputation: 4681

This is an ugly answer, but it might just do the trick if you plan on sticking to CSS. Hopefully someone will be able to point out a better way, however.

This idea relies on the fact that text-align: justify will spread out all lines of text but the last one (or the only one in case of just one line). Therefore, we're adding some useless text just to make sure there are at least two lines of text. Then, we try to hide the second line. I'm sure this could be improved upon:

h1 {
  width: 250px;
  height: 1.4em;
  margin-bottom: 0;
  background-color: green;
  text-align: justify;
}

h1 span {
  visibility: hidden;
  display:inline-block;
  line-height: 0px;
}

div {
  background-color: red;
  height: 100px;
  width: 250px;
}
<h1>Hello Plunker<span>make sure there are two lines, pretty please?</span></h1>
<div></div>

You can edit the jsfiddle here. To be honest, I guess it would be better to use JavaScript.

Upvotes: 1

gwcodes
gwcodes

Reputation: 5690

If you're willing to use JS, then http://fittextjs.com/ is worth a look. I don't think is achievable using CSS alone.

Upvotes: 1

Related Questions