首页 > 解决方案 > 为什么绝对定位元素会查看其兄弟元素?

问题描述

我已经看过为什么绝对定位元素取决于它的兄弟姐妹?,但我无法理解。因此,我创建了新问题,以便清楚地了解堆叠上下文。

.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,绝对定位元素取决于它的包含块。我错了吗?有什么问题?

绝对定位元素是其计算位置值是绝对或固定的元素。top、right、bottom 和 left 属性指定元素包含块边缘的偏移量。(包含块是元素相对于其定位的祖先。)如果元素有边距,则将它们添加到偏移量。

标签: csscss-positionz-index

解决方案


位置:绝对;使用position:relative/absolute查找最近的元素,并根据该元素确定其位置。

在您的情况下,由于您在图像中有position:relative,因此“Irene”文本将放置在图像的左上角。

要使“Irene”位于文档的左上角,您可以应用基于浏览器窗口的position:fixed ,或者删除“Irene”元素上方的所有position:absolute/relative 。


推荐阅读