0

I tried bunch of options for changing font depends of div width but I didn't find a solution.
So I want to font of h2 automatically be changed when I change div width. So can someone help me how to fix this.
I create the h2

var h2 = document.createElement('h2');
h2.innerHTML= "GET AN ESTIMATE OVER VIDEO CHAT";
h2.setAttribute("class", "naslov");

Then I insert it into div:

div2.appendChild(h2) + "\n";

And then I tried to change font size using css. So I tried next options:

h2{
font-size: 80%;
font-size: 1vw;
font-size: 1vh;
// and few more options
}

So can someone help me? Can I do it with css, or I should use JavaScript?

Milan Poznan
  • 307
  • 4
  • 18
  • are you trying something of that kind ? http://codepen.io/gc-nomade/pen/xEbraw (javascript should be required and min and max font-size value should be also set to keep text readable ....) – G-Cyrillus Sep 06 '16 at 14:56

2 Answers2

0

Best to use CSS. Also, to assign the class, use the className property:

h2.className = "naslov";

(setAttribute("class", ...) fails on old IE.)

Then in the CSS:

.naslov {
    font-size: 14px; /* or whatever */
}

Don't repeat the same style (font-size) within the block, it makes it invalid.

Or if you prefer not to use a class, you can apply the style directly:

h2.style.fontSize = "14px"; // or whatever
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Look you didn't understand question maybe, depends of div width, I want to get font size, if div is 200px font is 16px on example. – Milan Poznan Sep 06 '16 at 14:55
  • @MilanPoznan: I don't see that information in the question. I suppose "depends on div width" might cover it; wow do you want to emphasize when you're doing something that odd. – T.J. Crowder Sep 06 '16 at 14:57
  • @MilanPoznan: And it's already been asked and answered. – T.J. Crowder Sep 06 '16 at 14:58
0

Styles defined in css will be applied as soon as you will insert element in DOM. Its better to do it with css if possible. JavaScript should be an option when something can't be done in css.

var h2 = document.createElement('h2');
h2.innerHTML= "GET AN ESTIMATE OVER VIDEO CHAT";
h2.setAttribute("class", "naslov");

var div2 = document.querySelector('.div2');
div2.appendChild(h2) + "\n";
h2.naslov {
  font-size: 200%;
  color: blue;
}
<div class="div2"></div>
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95