Как расположить фоновое изображение элемента относительно документа / тела с переполнением: скрыто установлено родителем? - PullRequest
2 голосов
/ 21 января 2020

Проблема

Я хочу, чтобы background-image, то есть div.child из div.parent, был относительно позиционирован по отношению к body, с overflow: hidden, работающим для div.parent. Кроме того, я хочу, чтобы top: 0 из div.child относилось к body, а не div.parent, чтобы не имело значения, где div.parent располагается на оси Y (таким образом, top: из div.child не не нужно настраивать).

Демонстрация

body {
  position: relative;
  margin: auto;
  height: 1200px;
  width: 100%;
  
  background-image: url("https://images.unsplash.com/photo-1531251445707-1f000e1e87d0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=562&q=80");
  background-size: 100% auto;
  background-position: top center;
 
}

.parent {
  width: 80%;
  height: 300px;
  margin: 0 auto;
  margin-top: 200px;
  outline: 2px solid white; /* !!! Not visible anymore !!! */

  overflow: hidden; /* !!! Ignored by .child !!! */
}

.child {
  position: absolute;
  z-index: -1;
  width: 100%;
  height: 600px;
  top: -200px;
  left: 0;
  background-image: url("https://images.unsplash.com/photo-1531251445707-1f000e1e87d0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=562&q=80");
  background-size: 100% auto;
  background-position: top center;
  filter: invert(1);
}
<body>
  <div class="parent">
    <div class="child"></div>
  </div>
</body>

Есть два background-images, которые идеально совпадают (то же самое, один перевернут). Тем не менее, overflow: hidden, примененный к div.parent, больше не работает.

Поле div.parent обозначено белым outline.

Необходимое решение

Мне нужна коробка .parent, которая содержит тот же background-image, что и body, и независимо от того, где расположен этот .parent, всегда отображается фрагмент подложки background-image, примененной к body. Важно : .parent с background: transparent не работает. Это потому, что позже я буду использовать тот же background-image применительно к body, но тот, который отредактирован (как инвертированный в примере скрипта).

Ответы [ 2 ]

2 голосов
/ 21 января 2020

Если вам известны различные значения, применяемые к родительскому элементу, вы можете легко вычислить свойства фона и сохранить дочерний элемент относительно его родительского элемента:

body {
  position: relative;
  height: 1200px;
  margin:0;
  background-image: url("https://images.unsplash.com/photo-1531251445707-1f000e1e87d0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=562&q=80");
  background-size: 100% auto;
  background-position: top; 
  overflow:auto;
}

.parent {
  width: 80%;
  height: 300px;
  margin: 0 auto;
  margin-top: 200px;
  outline: 2px solid white; 
  position:relative;
  overflow:hidden;
  box-sizing:border-box;
}

.child {
  position: absolute;
  z-index: -1;
  /* same as border */
  top:-2px;
  left: -2px;
  right:-2px;
  bottom:-2px;
  /**/
  background-image: url("https://images.unsplash.com/photo-1531251445707-1f000e1e87d0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=562&q=80");
  background-size: calc(100%/0.8) auto;  /*0.8 = 80% of the width */
  background-position: top -200px center; /* Equal to margin*/
  filter: invert(1);
}
<body>
  <div class="parent">
    <div class="child"></div>
  </div>
</body>
0 голосов
/ 21 января 2020

Вам нужно добавить position:relative в родительский div. Проверьте приведенную ниже скрипку. Надеюсь, поможет.

body {
  position: relative;
  margin: auto;
  height: 1200px;
  width: 100%;
  
  background-image: url("https://images.unsplash.com/photo-1531251445707-1f000e1e87d0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=562&q=80");
  background-size: 100% auto;
  background-position: top center;
 
}

.parent {
  width: 80%;
  height: 300px;
  margin: 0 auto;
  margin-top: 200px;
  outline: 2px solid white; /* !!! Not visible anymore !!! */

  overflow: hidden; /* !!! Ignored by .child !!! */
  
  /*Add Relative to parent*/
  position: relative;
  
}

.child {
  position: absolute;
  z-index: -1;
  width: 100%;
  height: 600px;
  top: -200px;
  left: 0;
  background-image: url("https://images.unsplash.com/photo-1531251445707-1f000e1e87d0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=562&q=80");
  background-size: 100% auto;
  background-position: top center;
  filter: invert(1);
}
<body>
  <div class="parent">
    <div class="child"></div>
  </div>
</body>
...