疑似要素 ::before または ::after のコンテンツとして SVG を使用する方法はありますか? 質問する

疑似要素 ::before または ::after のコンテンツとして SVG を使用する方法はありますか? 質問する

::before選択した要素の前に SVG 画像を配置するために使用したいと思います。

#mydiv::before {
  content: '<svg ... code here</svg>';
  display: block;
  width: 22px;
  height: 10px;
  margin: 10px 5px 0 10px;
}

上記のコードはプレーンテキストを表示するだけです。仕様を確認しましたが、表示できる
内容にはいくつか制限があるようです。CSSプロパティ ソリューションが望ましいです。contentcontent

ベストアンサー1

はい、できます! 今テストしたところ、うまく動作しました。すばらしいです!

#test::before {
  content: url(path/to/your.svg);
  width: 200px;
  height: 200px;
}

または、SVG を CSS に直接配置したい場合は、次のようにします。

#test::before {
  content: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'%3E%3Ccircle cx='100' cy='50' r='40' stroke='black' stroke-width='2' fill='red'/%3E%3Cpolyline points='20,20 40,25 60,40 80,120 120,140 200,180' style='fill:none;stroke:black;stroke-width:3'/%3E%3C/svg%3E ");
  width: 200px;
  height: 200px;
}
<div id="test"></div>

SVG URL エンコーダーここで示すように、独自の SVG をフォーマットします。

おすすめ記事