2

I have the following CSS:

:root{
  --font-family: "Times", serif;
}

body{
  font-family: var(--font-family);
}

I also have a dropdown with the following values:

serif
sans-serif
'Montserrat', sans-serif;
'Source Code Pro', monospace;

I use this dropdown to set a CSS variable on the body:

let root = document.documentElement;

const fontSelect = document.querySelector("#font")

fontSelect.addEventListener("change", e => {
  console.log(fontSelect.value);
  root.style.setProperty('--font-family', fontSelect.value);
});

Each time, the correct console log happens, however only serif and sans-serif are being applied in Google Chrome. How can I make 'Montserrat', sans-serif; work?

https://codepen.io/EightArmsHQ/pen/3405e40daa7fcc7b17ff8a0e6a205b66

2
  • 1
    It should work if you remove the ; from your values Commented Jan 25, 2022 at 15:50
  • @Reyno ah yeah that works, thank you. If you'd like to answer with that I'll mark it correct. Commented Jan 25, 2022 at 15:57

1 Answer 1

2

You need to remove the ; from your values to make it valid.

let root = document.documentElement;

const fontSelect = document.querySelector("#font")

fontSelect.addEventListener("change", e => {
  console.log(fontSelect.value);
  root.style.setProperty('--font-family', fontSelect.value);
});
:root{
  --font-family: "Times", serif;
}

body{
  font-family: var(--font-family);
}
<select id="font">
  <option value="serif">Serif</option>
  <option value="sans-serif">Sans serif</option>
  <option value="'Montserrat', sans-serif">Montserrat</option>
  <option value="'Source Code Pro', monospace">Source Code Pro</option>
</select>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.