Insert a string of CSS into the HTML head with flexible positioning and container options
npx @tessl/cli install tessl/npm-insert-css@2.0.0insert-css is a lightweight JavaScript utility for dynamically inserting CSS strings directly into the HTML document head. It provides cross-browser compatibility and flexible positioning options for programmatic stylesheet injection.
npm install insert-cssvar insertCss = require('insert-css');Alternative access:
var insertCss = require('insert-css').insertCss;var insertCss = require('insert-css');
// Basic CSS insertion
var styleElement = insertCss('body { background: blue; }');
// CSS insertion with options
var styleElement = insertCss('body { color: red; }', {
container: document.querySelector('#app'),
prepend: true
});Inserts a CSS string into the DOM, creating or reusing style elements as needed.
/**
* Insert CSS string into the DOM
* @param {string} css - CSS string to insert (required)
* @param {Object} options - Configuration options (optional)
* @param {HTMLElement} options.container - Target container element, defaults to document.querySelector('head')
* @param {boolean} options.prepend - If true, inserts CSS at top of container instead of bottom
* @returns {HTMLElement} The style element that was created or reused
* @throws {Error} If css parameter is undefined
*/
function insertCss(css, options);Key Features:
styleSheet.cssText vs modern browsers' textContentUsage Examples:
var insertCss = require('insert-css');
// Insert CSS into head (default behavior)
insertCss('body { margin: 0; padding: 0; }');
// Prepend CSS for higher priority (useful for library defaults)
insertCss('.library-default { color: gray; }', { prepend: true });
// Insert CSS into custom container
var appContainer = document.querySelector('#app');
insertCss('.app-styles { font-family: Arial; }', {
container: appContainer
});
// The returned style element can be stored for reference
var myStyleElement = insertCss('p { line-height: 1.4; }');
console.log(myStyleElement.tagName); // 'STYLE'Error Handling:
The function throws an Error if the css parameter is undefined:
try {
insertCss(); // throws Error
} catch (error) {
console.log(error.message); // 'insert-css: You need to provide a CSS string. Usage: insertCss(cssString[, options]).'
}/**
* Options object for configuring CSS insertion behavior
*/
interface InsertCssOptions {
/** Target container element, defaults to document.querySelector('head') */
container?: HTMLElement;
/** If true, inserts CSS at top of container instead of bottom */
prepend?: boolean;
}document object)