CSS in JavaScript

Why can’t we use CSS code that has hyphens?

is there any method to fix this or no?

image

Because it’s not margin-top in JS. It’s marginTop

Though if you’re going to be changing multiple properties, it might make more sense to put those all in a class and add the class name dynamically.

In css

.newClass {
  border: 1px solid red;
  margin-top: 10px;
}

In JS

function ForChild(child) {
   child.classList.add("newClass");
}

This gives you the benefit of having ALL the css configuration in one place and you don’t have to hunting for it through JS.

3 Likes

Because in js the hyphen is the minus operator.

1 Like

I did it without hyphen with CamelCase and without, still didn’t work.

image

space-around has a hyphen in it. Things inside strings can contain hyphens.
element.style.justifyContent = "space-around";

See:
https://www.w3schools.com/jsref/prop_style_borderstyle.asp
https://www.w3schools.com/jsref/prop_style_margintop.asp
https://www.w3schools.com/jsref/prop_style_backgroundcolor.asp
https://www.w3schools.com/jsref/prop_style_justifycontent.asp

I got it

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.