Set multiple values ​​for one css attribute

Is it possible to set two values ​​for one attribute in a CSS identifier, for example.

height: 12m; height: 12 in the morning;

for one id? I know that this can be done using CSS, but I want to change the height using javascript and have both values ​​for the same attribute, so that "em" functions as a reserve for browsers that do not support "rem".

Example:

function updateHeight() {
  var testElem = document.getElementById("testId");
  testElem.style.height = "12em";
  testElem.style.height = "12rem";
  //testElem.style.height = "12em; 12rem;"; doesn't work, applies "12em"
}
#testId {
  height: 8em;
  height: 8rem;
  background-color: black;
  color: white;
}
<!DOCTYPE html>
<html>

<head>
  <title>Test</title>
  <meta charset="utf-8" />
</head>

<body>
  <div id="testId">
    BlaBla
  </div>
  <button onclick="updateHeight()">Bla</button>
</body>

</html>
Run codeHide result
+4
source share
2 answers

You can use a class instead

function updateHeight() {
  var testElem = document.getElementById("testId");
  testElem.classList.add('high');
}
#testId {
  height: 8em;
  height: 8rem;
  background-color: black;
  color: white;
}

#testId.high { /* remember that ID is more specific than class */
  height: 12em;
  height: 12rem;
}
<!DOCTYPE html>
<html>

<head>
  <title>Test</title>
  <meta charset="utf-8" />
</head>

<body>
  <div id="testId">
    BlaBla
  </div>
  <button onclick="updateHeight()">Bla</button>
</body>

</html>
Run codeHide result

Or, if this value is dynamic, you may have to insert a style tag to support CSS cascading

function updateHeight() {

  var value    = 12; // or something dynamic
  var styles   = '#testId {height: '+value+'em; height: '+value+'rem;}';
  var tag      = document.createElement('style');

  tag.innerHTML = styles;

  document.querySelector('head').appendChild(tag);

}
#testId {
  height: 8em;
  height: 8rem;
  background-color: black;
  color: white;
}
<!DOCTYPE html>
<html>

<head>
  <title>Test</title>
  <meta charset="utf-8" />
</head>

<body>
  <div id="testId">
    BlaBla
  </div>
  <button onclick="updateHeight()">Bla</button>
</body>

</html>
Run codeHide result
+3
source

, . CSS Cascade:

, , .

cascade, " ".

: , ( ).

,

height: 8em;
height: 8rem;

2 height: 8em 8rem. , .

- , , .

- , , . specified defaulting ( , height inherited property).

JavaScript . setProperty, IDL .style, CSS, :

  • , , CSS , , CSS .

  • CSS CSS.

:

  • cssText IDL :

    testElem.style.cssText += "; height: 12em; height: 12rem; ";
    
  • . , , .

    testElem.style.height = "12rem";
    if(!testElem.style.height) testElem.style.height = "12em";
    
  • inline. , CSS .

+2

All Articles