【发布时间】:2019-08-08 23:24:27
【问题描述】:
我已经看过Why absolute positioned element depends on it's sibling?,但我无法理解。因此,我创建了一个新问题,以便清楚地了解堆叠上下文。
.swiper__img {
position: absolute;
left: 50%;
top: 50%;
width: 100%;
transform: translate(-50%,-50%);
transition: top .5s;
width: 400px;
cursor: pointer;
}
.swiper__img:hover {
top: 45%;
}
.swiper__img:hover .swiper__img__left,
.swiper__img:hover .swiper__img__right {
opacity: 0.5;
}
.swiper__img:hover .swiper__img__left { left: -5%; }
.swiper__img:hover .swiper__img__right { right: -5%; }
.swiper__img__main {
position: relative;
background-image: url('https://user-images.githubusercontent.com/35518072/62710517-707ecc80-ba32-11e9-825d-387e37b71eba.png');
background-repeat: no-repeat;
background-size: cover;
padding-top: 150%;
z-index: 1;
}
.swiper__img__left {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
background-image: url('https://user-images.githubusercontent.com/35518072/62710476-52b16780-ba32-11e9-85ce-23d2421e641e.png');
background-repeat: no-repeat;
background-size: cover;
padding-top: 150%;
transition: all .5s;
}
.swiper__img__right {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
background-image: url('https://user-images.githubusercontent.com/35518072/62710535-75dc1700-ba32-11e9-9b05-80bc6d9980a7.png');
background-repeat: no-repeat;
background-size: cover;
padding-top: 150%;
transition: all .5s;
}
.swiper__img__title {
font-size: 20px;
position: absolute;
left: 0;
top: 0;
color: white;
letter-spacing: 5px;
z-index: 2;
font-weight: 100;
font-family: 'Libre Caslon Display', serif;
}
body {
transition: background-color .5s;
}
<div id="fullpage" class="swiper">
<div class="swiper">
<div class="section">
<div class="swiper__img">
<div class="swiper__img__main"></div>
<div class="swiper__img__left"></div>
<div class="swiper__img__right"></div>
<h2 class="swiper__img__title">IRENE</h2>
</div>
</div>
<div class="section">
<div class="swiper__img">
<div class="swiper__img__main"></div>
<div class="swiper__img__left"></div>
<div class="swiper__img__right"></div>
<h2 class="swiper__img__title">IRENE</h2>
</div>
</div>
</div>
</div>
我预计“IRENE”是文档的左上角,但这取决于它的图像。在这种情况下,我想了很多时间来理解堆叠上下文。但是,这对我来说太复杂了,我无法解决这个问题。我该如何处理?这种情况下缺少什么?
更新
我想知道的是为什么文本取决于position:relative 元素,它是兄弟元素?
根据 MDN,绝对定位元素取决于它的包含块。我错了吗?有什么问题?
绝对定位元素是指计算位置的元素 值是绝对的或固定的。顶部、右侧、底部和左侧 属性指定从元素包含的边缘的偏移量 堵塞。 (包含块是相对于它的祖先 元素已定位。)如果元素有边距,则将它们添加到 偏移量。
【问题讨论】:
-
@Huangism 感谢您的关心,但我已经练习并理解了基本概念。
-
对不起,如果您确实了解基础知识,那么您将不会问这个问题。默认情况下,顶部、左侧、右侧和底部的值设置为
auto。如果你不设置它们,那么定位将是它在代码中的位置,所以它会出现在你之前的元素附近
标签: css css-position z-index