marrem97 marrem97 - 5 months ago 9
HTML Question

Set multiple values for one css attribute

Is it possible to set two Values for a single attribute on a CSS ID, e.g.


height: 12em; height: 12rem;


for a single id?
I know it's possible to do this with CSS, but I want to change the height via javascript, and have both values on one attribute, so that 'em' functions as a fallback for Browsers not supporting '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>




Answer

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>

Or if the value is dynamic, you'd probably have to insert a style tag to be able 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>

Comments