
:has() 擬似クラスで作るカードデザイン
便利なCSSの擬似クラス「:has() 」
:has() は 親要素が子要素を条件にスタイルを変えられる 便利なCSSの擬似クラスです! article:has(img) を使うと、 画像を含む <article> にだけ特定のスタイルを適用できる ようになります。
🎯 :has() の基本的な使い方 (CSS
article:has(img) {
border: 2px solid red;
background: #4f4f4f;
}
✅ 画像が含まれる <article> だけ 枠線&背景色をつける
🎨 実用例:カードデザイン
.card:has(img) {
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
→ 画像付きカードだけリッチなデザインに!
⛔ :has() の注意点
一部のブラウザ(特に古いSafari)では非対応
でも、最近のChrome・Firefox・EdgeではOK!
疑似クラスの中でネスト( :has(:has()) )はできない
パフォーマンスに注意(特に body:has(.modal) みたいな全体適用は慎重に)
💡 応用テク
.card:has(button) {
border: 3px solid blue;
}
📌 フォームが空なら「入力してください」メッセージを表示
form:not(:has(input:valid))::after {
content: "入力してください";
color: red;
}
デモを用意したので、ぜひアレンジを加えて試してみてください。
デモ(HTML)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>:has() Demo</title>
</head>
<body>
<div class="container">
<div class="card">
<img src="https://via.placeholder.com/300" alt="Sample Image">
<div class="card-content">
<h3>カード1</h3>
<p>画像付きのカードです。</p>
</div>
</div>
<div class="card">
<div class="card-content">
<h3>カード2</h3>
<p>画像なしのカードです。</p>
</div>
</div>
<div class="card">
<img src="https://via.placeholder.com/300" alt="Sample Image">
<div class="card-content">
<h3>カード3</h3>
<p>これも画像付きのカード!</p>
</div>
</div>
</div>
</body>
</html>
デモ(CSS)
* {
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: 'Arial', sans-serif;
}
body {
background-color: #f4f4f4;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
padding: 2rem;
}
.container {
display: grid;
gap: 20px;
max-width: 900px;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
}
.card {
background: white;
border-radius: 12px;
overflow: hidden;
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
transition: transform 0.3s ease;
}
.card img {
width: 100%;
height: auto;
display: block;
}
.card-content {
padding: 20px;
}
.card h3 {
font-size: 1.5rem;
margin-bottom: 10px;
}
.card p {
font-size: 1rem;
color: #555;
}
.card:has(img) {
border: 2px solid #4f4f4f;
}
.card:hover {
transform: translateY(-10px);
}