Skip to content

useStyleTag

Category
Export Size
513 B
Last Changed
4 months ago

Inject reactive style element in head.

Demo

Edit CSS:

ID: vueuse_styletag_1

Loaded: true

Usage

Basic usage

Provide a CSS string, then useStyleTag will automatically generate an id and inject it in <head>.

ts
import { 
useStyleTag
} from '@vueuse/core'
const {
id
,
css
,
load
,
unload
,
isLoaded
,
} =
useStyleTag
('.foo { margin-top: 32px; }')
// Later you can modify styles
css
.
value
= '.foo { margin-top: 64px; }'

This code will be injected to <head>:

html
<style id="vueuse_styletag_1">
  .foo {
    margin-top: 64px;
  }
</style>

Custom ID

If you need to define your own id, you can pass id as first argument.

ts
useStyleTag
('.foo { margin-top: 32px; }', {
id
: 'custom-id' })
html
<!-- injected to <head> -->
<style id="custom-id">
  .foo {
    margin-top: 32px;
  }
</style>

Media query

You can pass media attributes as last argument within object.

ts
useStyleTag
('.foo { margin-top: 32px; }', {
media
: 'print' })
html
<!-- injected to <head> -->
<style id="vueuse_styletag_1" media="print">
  .foo {
    margin-top: 32px;
  }
</style>

Type Declarations

ts
export interface UseStyleTagOptions extends ConfigurableDocument {
  /**
   * Media query for styles to apply
   */
  
media
?: string
/** * Load the style immediately * * @default true */
immediate
?: boolean
/** * Manual controls the timing of loading and unloading * * @default false */
manual
?: boolean
/** * DOM id of the style tag * * @default auto-incremented */
id
?: string
/** * Nonce value for CSP (Content Security Policy) * * @default undefined */
nonce
?: string
} export interface UseStyleTagReturn {
id
: string
css
:
ShallowRef
<string>
load
: () => void
unload
: () => void
isLoaded
:
Readonly
<
ShallowRef
<boolean>>
} /** * Inject <style> element in head. * * Overload: Omitted id * * @see https://vueuse.org/useStyleTag * @param css * @param options */ export declare function
useStyleTag
(
css
:
MaybeRef
<string>,
options
?: UseStyleTagOptions,
): UseStyleTagReturn

Source

SourceDemoDocs

Contributors

Anthony Fu
sibbng
IlyaL
Anthony Fu
James Wragg
SerKo
BeamDong
mrayi
Jelf

Changelog

v13.2.0 on
fa2c0 - feat: support passing nonce (#4749)
v12.8.0 on
7432f - feat(types): deprecate MaybeRef and MaybeRefOrGetter in favor of Vue's native (#4636)
v12.0.0-beta.1 on
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)

Released under the MIT License.

Build faster with AI
New Masterclass to help you leverage AI in your Vue workflow
Get Early Access