The thing with css is that sometimes the css will output before a page is ready, and the web browser will display a message saying essentially that the css layout output is too early because the page has not output yet, this How to guide is the answer.
OK, to the point, it’s very nice that CSS variables can be dynamically initialized with JavaScript.
This is accomplished from a JavaScript script and function in the header of a webpage, define the function, utilize document.write to output all css using the not as known, but very powerful
JavaScripts backtick multi-line string and also using dynamic variables within Javascripts multi-line string, then invoke the function immediately. Notice the following code example.
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<!-- How to use Dynamic CSS, Javascript powered CSS -->
<script>
function dynamic_css_js() {
var font_color = '';
var iphone_mobile_phone = False;
var android_mobile_phone = True;
if ( iphone_mobile_phone ) {
font_color = "green";
}
else if ( android_mobile_phone ) {
font_color = "yellow";
}
document.write(`
#cool {
color: ${font_color};
}
<!-- You may output an external css stylesheet -->
<link rel="stylesheet" href="/html/styles.css">
<!-- You may also output another script though be sure to do the special output of the closing script tag -->
<script> alert("hey there"); </` + `script>
`);
}
dynamic_css_js();
</script>
</head>
<body>
<h1 id="cool">Hello Web Developers</h1>
</body>
</html>
I like to create blog posts of value, send me an email at opensource3 at yahoo dot com if this post has been helpful to you.
Happy Coding!