I have a question regarding style tags and Javascript. Many plugins or scripts come with a separate CSS file for styling. So, is it bad practice to avoid this, and use a style tag and append it to the head of the page, to then use those styles for your plugin?
For example, this code:
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.hg-grid-item-4{ width: calc(24.25% - '+Options.padding * 2+'px); padding: '+Options.padding+'px; float: left; margin-bottom: 1%}';
document.getElementsByTagName('head')[0].appendChild(style);
would add some styling to the website without needing an external CSS stylesheet. Would this cause problems in older browsers?
Also, as you can see in my example, I used a variable for the padding and the width. Is there a way of doing this if you dedice to use an external CSS? Thanks in advance!
Adding the style tag to the DOM with JavaScript is totally legal for JavaScript to do, however, this is not considered "best practice."
When writing code, it best to separate the view from your application logic. The easiest way to do this is to put all of your styles in a CSS file. Also, it has the added benefit of making your code easier for other developers to understand.
For more information:
In regards to your variable padding question, in vanilla CSS, this is not possible, in order to use variables in CSS, you would need to use a CSS Preprocessor, like SASS or LESS . However, I think this would be overkill for your problem, you can make flexible styles using Flexbox or using percents instead of fixed margins or padding.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.