37

I have a div with 70% width, and here’s what I want to do:

  • Put some words in that div
  • Adapt font size so that those words occupy all div width


Is this possible with only css? Here is my code:

.parent {
  width:70%;
  height:auto;
  min-height:100px;
  background:red;
  font-size:10vw;
}
Please help me to change the font-size dynamically to the parent class
<hr>
<div class="parent">
  This Text
</div>

Note: the div size is responsive, this is important. Thanks in advance!

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Engkus Kusnadi
  • 2,386
  • 2
  • 18
  • 40

5 Answers5

6

Perhaps not quite what you're looking for, but something - You can make both the font and the element relative to view width.

p {
  font-size: 5vw;
  background-color: red;
  width: 50vw;
}
<p>
  I'm a P!
</p>
Anthony Astige
  • 1,919
  • 1
  • 13
  • 18
  • This is as close as it gets. If your text is static, you can hardcode its width to however many vw's you need to get it just right. If you're dynamically generating text, CSS isn't enough and you need to mix in some JS. – Different55 Jun 11 '23 at 18:02
6

You just have to add display: inline; in your code

.parent {
  width: 70%;
  height: auto;
  min-height: 100px;
  background: red;
  font-size: 10vw;
  display: inline;
}
<div class="parent">
  This Text
</div>
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Marina
  • 1,682
  • 1
  • 20
  • 25
  • It works well but maybe need improvements to work fully. – UserOfStackOverFlow Dec 09 '21 at 18:20
  • 3
    Unless I'm misunderstanding this answer or the question, this is backwards, and doesn't solve the problem - adding `display: inline` to parent div adapts it's size to text, not the other way around. – ja2142 Jul 23 '22 at 21:52
0
**You can change font-size:10vh;**
        .parent {
      width:70%;
      height:auto;
      min-height:100px;
      background:red;
      color:white;
      font-size:10vh;
    }
    Please help me to change the font-size dynamically to the parent class
    <hr>
    <div class="parent">
      Text
    </div>
Saw Saw
  • 11
-2

Yes but I think you need to use JS(jQuery).

JS:

$(function(){

var box = $('.box');
var boxWith = box.width();

$('.box h1').css('font-size',boxWith);

});

https://jsfiddle.net/moongod101/sdfaatp8/

Felix Fong
  • 969
  • 1
  • 8
  • 21
-3

Here, I Updated it.... JS Fiddel

try to use

css

.parent 
 {
      width:70%;
      height:auto;
      min-height:100px;
      background:red;
      font-size:10vw;          
  }



span{
      display:inline-block;
      transform:scale(1.8,1);
      -webkit-transform:scale(3,1);
 }

HTML

<div class="parent">
  <span>This Text</span>
 </div>
shivani
  • 980
  • 1
  • 8
  • 29