Относительное позиционирование

Рейтинг: 0Ответов: 2Опубликовано: 24.01.2023

Есть 2 родителя

  1. Первый родитель имеет свойство position: relative;
  2. Второй родитель который расположен в первом, имеет свойство position: absolute;

Вопрос в том, если во втором родиле расположен элемент который необходимо присвоить абсолютное позиционирование относительно не второго, а первого элемента.

Возможно и каким образом это сделать?

.mn {
   position: relative;
   background: red;
   width: 500px;
   height: 500px;
}
.bl {
   position: absolute;
   height: 100px;
   bottom:0;
   background: blue;
   width: 100%;
}
.center {
   position: absolute;
   left: 50%;
   top: 50%;
   width: 50px;
   height: 50px;
   background: ghostwhite;
   transform: translate(-50%, -50%);
}
<div class='mn'>
   <div class='bl'>
      <div class='center'></div>
  </div>
</div>

Ответы

▲ 2

Вариант 1

.mn {
  position: relative;
  background: red;
  width: 500px;
  height: 500px;
  display: flex;
  flex-direction: column;
}

.bl {
  height: 100px;
  background: blue;
  width: 100%;
  margin-top: auto;
}

.center {
  position: absolute;
  left: 50%;
  top: 50%;
  width: 50px;
  height: 50px;
  background: ghostwhite;
  transform: translate(-50%, -50%);
}
<div class='mn'>
  <div class='bl'>
    <div class='center'></div>
  </div>
</div>

Вариант 2

:root {
  --parent-height: 500px;
  --child-height: 100px;
}

.mn {
  position: relative;
  background: red;
  width: 500px;
  height: var(--parent-height);
}

.bl {
  position: absolute;
  height: var(--child-height);
  bottom: 0;
  background: blue;
  width: 100%;
}

.center {
  position: absolute;
  left: 50%;
  top: calc(((var(--parent-height) - var(--child-height)) / 2) * -1);
  width: 50px;
  height: 50px;
  background: ghostwhite;
  transform: translateX(-50%);
}
<div class='mn'>
  <div class='bl'>
    <div class='center'></div>
  </div>
</div>

▲ 1

.mn {
   position: relative;
   background: orange;
   width: 200px;
   height: 200px;
}
.bl {
   position: absolute;
   height: 50px;
   bottom:0;
   background: lime;
   width: 100%;
   display: contents; /*!!!!!!!!!!!!!!*/
}
.center {
   position: absolute;
   left: 50%;
   top: 50%;
   width: 25px;
   height: 25px;
   background: red;
}
<div class='mn'>
   <div class='bl'>
      <div class='center'></div>
  </div>
</div>

но имейте ввиду, при таком подходе второй блок удаляется из макета, потому, этот вариант может подойти только если второй блок используется лишь как логический контейнер.

если появятся еще идеи, дополню, но пока всё.