2020.10.15

HTML・CSS

CSS疑似要素のcontentプロパティにjQueryで設定したカスタムデータ属性の値を指定

デモページはこちら

CSS疑似要素のcontentプロパティにjQueryで設定したカスタムデータ属性の値を指定します。以下のhtml構造でテストします。デモページではクラス名boxのdivタグは12個並べています。

<div class="container">
	<div class="box">
		<figure class="photo">
			<img src="images/photo01.jpg" alt="">
		</figure>
		<h3>タイトル01</h3>
		<p>ダミーテキストダミーテキストダミーテキスト</p>
	</div>
	<div class="box">
		<figure class="photo">
			<img src="images/photo02.jpg" alt="">
		</figure>
		<h3>タイトル02<br>タイトル02</h3>
		<p>ダミーテキストダミーテキストダミーテキスト</p>
	</div>
	<div class="box">
		<figure class="photo">
			<img src="images/photo03.jpg" alt="">
		</figure>
		<h3>タイトル03<br>タイトル03<br>タイトル03</h3>
		<p>ダミーテキスト</p>
	</div>
</div>

CSSはクラス名photoのfigureタグに疑似要素beforeを設定します。contentプロパティでattr(data-index);のようにカスタムデータ属性data-indexを指定します。クォーテーションの記述は必要ありません。

.photo {
	position: relative;
}
.photo:before {
	position: absolute;
	top: 0;
	right: 0;
	bottom: 0;
	left: 0;
	display: flex;
	justify-content: center;
	align-items: center;
	font-family: 'Patua One', cursive;
	font-size: 2rem;
	font-weight: 400;
	color: #fff;
	word-break: break-all;
	content: attr(data-index);
}

jQueryは変数photo_countに0をセットし、クラス名boxのdivタグの数だけカウントアップして処理します。変数photo_countが10未満の場合、クラス名photoのfigureタグにカスタムデータ属性data-index="01"からdata-index="09"を設定し、変数photo_countが10以上の場合、クラス名photoのfigureタグにカスタムデータ属性data-index="10"以上を設定します。

$(function() {
	var photo_count = 0;
	$('.box').each(function(){
		photo_count++;
		if(photo_count < 10){
			$(this).find('.photo').attr('data-index','0' + photo_count);
		}else{
			$(this).find('.photo').attr('data-index',photo_count);
		}
	});
});

関連記事

2024.09.05

HTML・CSS

radial-gradientで作る水玉模様

background-imageプロパティのradial-gradientで水玉模様を作成します。わかりやすいように背景を繰り返し前と繰り返し後で比較します。デ…

2020.08.23

HTML・CSS

マウスオーバー時にCSSのみでフェードイン・フェードアウトを実装する場合の注意点

マウスオーバー時にCSSのみでフェードイン・フェードアウトを実装する場合、display: none;で非表示、マウスオーバー時にdisplay: block;…

2024.09.25

HTML・CSS

marginの相殺について

兄弟要素と親子要素で発生するmarginの相殺について確認します。また相殺が発生しない例外についても確認します。デモページはこちら 共通のCSSは以下になります…

2025.08.14

HTML・CSS

1行のテキストの均等割りについて

デザイン上テキストが1行に限定されている場合のテキストの均等割りを確認します。デモページはこちら 以下のhtml構造で確認します。 CSSは以下になります。te…

2025.05.08

HTML・CSS

text-decorationを利用した文字の下線

text-decorationプロパティを利用して複数行の文字に下線を引きます。複数行に対応させるため、inline要素に適用します。デモページはこちら 以下の…

上に戻る