element()

Limited availability

This feature is not Baseline because it does not work in some of the most widely-used browsers.

Experimental: これは実験的な機能です。
本番で使用する前にブラウザー互換性一覧表をチェックしてください。

element()CSS関数で、任意の HTML 要素から生成された <image> 値を定義します。この画像は動的で、HTML 要素が変更されると、この関数の結果を使う CSS プロパティが自動的に更新されます。

特に便利な使い道としては、HTML の <canvas> 要素の画像を背景に使うというものです。

Gecko ブラウザーでは、標準外の document.mozSetImageElement() メソッドで背景として使われる要素を既定の CSS の背景要素と取り替えることができます。

構文

css
element(id)

ここで:

id

背景として使う要素の ID です。要素の HTML 属性 #id に定義されているものです。

以下の例は、 -moz-element() に対応している Firefox のビルドが必要です。

いくらか現実的な例

この例では hidden 状態の <div> を背景に使います。背景要素はグラデーションを使うだけでなく、背景の一部として描画されるテキストも含んでいます。

html
<div
  style="width:400px; height:400px; background:-moz-element(#myBackground1) no-repeat;">
  <p>This box uses the element with the #myBackground1 ID as its background!</p>
</div>

<div style="overflow:hidden; height:0;">
  <div
    id="myBackground1"
    style="width:1024px; height:1024px; background-image: linear-gradient(to right, red, orange, yellow, white);">
    <p style="transform-origin:0 0; rotate: 45deg; color:white;">
      This text is part of the background. Cool, huh?
    </p>
  </div>
</div>

"myBackground1" という ID を持つ <div> 要素が、"This box uses the element with the #myBackground1 ID as its background!" という段落を含むコンテンツの背景に使われています。

ページプレビュー

この Vincent De Oliveira の例に基づいた例は、 <div id="css-source"> のプレビューを <div id="css-result"> の中に生成します。

HTML

html
<div id="css-source">
  <h1>Page Preview</h1>
</div>
<div id="css-result"></div>

CSS

css
#css-result {
  background: -moz-element(#css-source) no-repeat;
  width: 256px;
  height: 32px;
  background-size: 80%;
  border: dashed;
}

結果

仕様書

Specification
CSS Images Module Level 4
# element-notation

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
element()
Experimental

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Partial support
Partial support
No support
No support
Experimental. Expect behavior to change in the future.
Requires a vendor prefix or different name for use.
Has more compatibility info.

関連情報