<button type="button">z-index の競合を解決する</button>
<div class="container">
<nav>
<h2>メニューに hover してください</h2>
<ul class="sidebar">
<li class="mouseover-menu">
メニュー
<ul class="mouseover-menu__child">
<li class="mouseover-menu__child-menu">
子メニュー 1
</li>
<li class="mouseover-menu__child-menu">
子メニュー 2
</li>
<li class="mouseover-menu__child-menu">
子メニュー 3
</li>
</ul>
</li>
</ul>
</nav>
<main class="contents">
<section>
<h2>absolute を内包するコンテンツ</h2>
<ul>
<li class="card" data-is-isolate="false">
<div class="card__badge">NEW</div>
<div class="card__bar">ねこ</div>
<img src="https://placehold.jp/3d4070/ffffff/300x200.png?text=dummy" />
<p class="card__text">コンテンツ 1</p>
<li>
</ul>
</section>
</main>
</div>
/* button 押下後 */
.card {
&[data-is-isolate="true"] {
isolation: isolate;
}
}
/* z-index */
.card {
&__bar {
z-index: 1;
}
&__badge {
z-index: 2;
}
}
.mouseover-menu {
&__child {
z-index: 1;
}
}
/* card */
.card {
position: relative;
border: 1px solid #666;
border-radius: 5px;
&__bar {
display: flex;
justify-content: center;
align-items: center;
position: absolute;
top: 10px;
left: 0;
width: 100%;
height: 30px;
background-color: rgba(255, 192, 203, 0.5);
font-size: 12px;
}
&__badge {
display: flex;
justify-content: center;
align-items: center;
position: absolute;
top: 5px;
left: 5px;
width: 30px;
height: 30px;
border-radius: 50%;
background-color: #ff0000;
color: #fff;
font-size: 8px;
font-weight: bold;
}
&__text {
padding: 10px;
font-size: 13px;
}
}
/* mouseover-menu */
.mouseover-menu {
position: relative;
display: flex;
align-content: center;
flex-wrap: wrap;
width: 100%;
height: 50px;
padding: 0 10px;
border-top: 1px solid #666;
border-bottom: 1px solid #666;
font-size: 13px;
&:hover {
.mouseover-menu__child {
display: block;
}
}
& + & {
border-top: 1px solid #666;
}
&__child {
position: absolute;
top: 0;
left: calc(100% - 20px);
display: none;
width: max-content;
background-color: #fff;
border: 1px solid #666;
border-radius: 5px;
}
&__child-menu {
padding: 10px;
& + & {
border-top: 1px solid #666;
}
}
}
/* layout & other parts */
.container {
display: flex;
padding: 20px 0;
}
.contents {
margin-left: 30px;
}
nav {
width: 300px;
background-color: #f0f0f0;
}
h2 {
margin-bottom: 20px;
font-size: 18px;
}
/* おめかし button */
button {
-webkit-appearance: none;
appearance: none;
padding: 10px;
border: none;
border-radius: 5px;
background-color: #23abdd;
color: #fff;
font-size: 15px;
font-weight: bold;
cursor: pointer;
&:hover {
opacity: 0.8;
}
}
/* reset */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
img {
vertical-align: bottom;
}
li {
list-style: none;
}
View Compiled
const button = document.querySelector('button');
const card = document.querySelector('[data-is-isolate]');
button.addEventListener('click', () => {
card.dataset.isIsolate = "true";
});
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.