ページのマークアップと CSS を変更する機能があり、余分な要素 (など) を追加したくない<strong>
場合は、CSS カウンターの利用を試みることができます。カウンターは非常に優れたブラウザー サポートを備えています。
カウンターを使用すると、図に自動番号を付けたり、コンテンツの前に「図 X」というテキストを追加したり、マークアップに追加の変更を加えずにスタイルを設定したりできます。これの大きな利点は、手動で番号を付ける必要がなく、注文の将来の変更について心配する必要さえないことです。CSS が自動的に処理します。必要なスタイリングを追加することもできます。
以下はサンプル スニペットです。
body {
counter-reset: figure; /* Initializes the counter to 0 */
}
p {
counter-increment: figure; /* Increment the counter everytime p tag is encountered in DOM */
}
p:before {
content: "Figure " counter(figure)" "; /* Set Figure + Counter value as content */
font-weight: bold;
color: red;
}
<p>Lorem Ipsum...</p> <!-- Counter = 1, Before Content = Figure 1 -->
<p>Lorem Ipsum...</p> <!-- Counter = 2, Before Content = Figure 2 -->
<p>Lorem Ipsum...</p> <!-- Counter = 3, Before Content = Figure 3 -->
<p>Lorem Ipsum...</p> <!-- Counter = 4, Before Content = Figure 4 -->
<p>Lorem Ipsum...</p> <!-- Counter = 5, Before Content = Figure 5 -->
すべての<p>
タグに番号を付けるのではなく、特定の<p>
タグのみに番号を付けたい場合は、以下のスニペットのように一意のクラスを指定できます。(注:追加のクラスを追加しても、太字のテキストは "Figure X" テキストのみに制限されており、その内容全体には適用されません<p>
)。
body {
counter-reset: figure;
}
p.count {
counter-increment: figure;
}
p.count:before {
content: "Figure " counter(figure)" ";
font-weight: bold;
color: red;
}
<p class='count'>Lorem Ipsum...</p>
<p>Lorem Ipsum...</p>
<p class='count'>Lorem Ipsum...</p>
<p class='count'>Lorem Ipsum...</p>
<p>Lorem Ipsum...</p>
質問で提供されたスニペットのように、「Figure x」テキストが 内の 2 番目の段落にのみ適用される場合div class='imgcontainer'
でも、次のスニペットのように余分なクラスを追加せずにこれを行うことができます。
body {
counter-reset: figure;
}
.imgcontainer > p + p {
counter-increment: figure;
}
.imgcontainer > p + p:before {
content: "Figure " counter(figure);
padding-right: 1ch; /* More padding-right means more space between Figure x and text */
font-weight: bold;
color: red;
}
<div class='imgcontainer'>
<p>
<img src='http://placehold.it/100/100'>
</p>
<p>Some Description</p>
</div>
<div class='imgcontainer'>
<p>
<img src='http://placehold.it/100/100'>
</p>
<p>Some Description</p>
</div>
<div class='imgcontainer'>
<p>
<img src='http://placehold.it/100/100'>
</p>
<p>Some Description</p>
</div>
<div class='imgcontainer'>
<p>
<img src='http://placehold.it/100/100'>
</p>
<p>Some Description</p>
</div>
注: 1ch
要素のフォントの「0」文字の幅を意味します。ch
ユニットはブラウザのサポートが低く、例としてのみ使用しました。px
の代わりにまたはem
または そのような単位を使用できますch
。