首页 > 解决方案 > 如何定位一个元素,就好像它是相对的但有属性就好像它是绝对的?

问题描述

假设我要制作一个div。我想相对定位它,比如在通常位置的右侧 100 像素。但是,我希望所有其他 div 忽略它,就好像它是绝对定位一样。我该怎么做?

标签: htmlcss

解决方案


有2个元素在另一个。第一个简单的position: absolute;while inner has position: relative; right: 100px。将需要的任何内容放入其中.inner

body {
    counter-reset: foo-counter;
}

div {
  width: 100px;
  height: 100px;
  display: inline-block;
  border: 1px solid rgba(0, 0, 0, .3);
  background-color: rgba(0, 0, 0, .1);
  text-align: center;
}

div:not(.pop):before {
  counter-increment: foo-counter;
  content: "# " counter(foo-counter);
}

.pop {
  text-align: left;
  position: absolute;
  background-color: rgba(120, 0, 0, .7);
}

.pop:before {
  counter-increment: foo-counter;
  content: "# " counter(foo-counter);
}

.inner {
  position: relative;
  top: 20px;
  right: 20px;
  background-color: rgba(0, 40, 0, .2);
}
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div class="pop"><div class="inner"></div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>


推荐阅读