【问题标题】:How to absolutely position a div right outside the main one? [duplicate]如何将 div 绝对定位在主目录之外? [复制]
【发布时间】:2020-11-29 06:23:39
【问题描述】:

假设我有一些这样的代码:

.a {
  width: 400px;
  height: 150px;
  border: 1px solid #777;
  position: relative;
}

.b {
  position: absolute;
  top: 30%;
  right: -33px;
}

.c {
  position: absolute;
  top: 50%;
  right: -88px;
}
<div class="a">
  <div class="b">hello</div>
  <div class="c">testing longer</div>
</div>

如果您运行 sn-p,您将看到所需的行为,其中 b 和 c 都位于 a 元素的右边缘。

我遇到的唯一问题是我的网站b 和c 有动态内容(我不知道他们会提前做什么)。是否可以以某种方式修改b 和c 的right 属性,这样我就不必硬编码值,它们仍将位于a 的外边缘?

【问题讨论】:

  • 左:100% 而不是右

标签: javascript html css css-position


【解决方案1】:

你可以使用:

  • left: 100% 或
  • right: 0 和 transform: translateX(100%)

示例:

.a {
  width: 400px;
  height: 150px;
  border: 1px solid #777;
  position: relative;
}

.b, .c {
  position: absolute;
  right: 0;
  transform: translateX(100%);
}

.b {
  top: 30%;
}

.c {
  top: 50%;
}
<div class="a">
  <div class="b">hello</div>
  <div class="c">testing longer</div>
</div>

我可能会更进一步,用另一个元素包装 .b 和 .c,这样你也可以摆脱硬编码 top。

.a {
  width: 400px;
  height: 150px;
  border: 1px solid #777;
  position: relative;
}

.d {
  position: absolute;
  top: 50%;
  right: 0;
  transform: translate(100%, -50%);
}

.c {
  margin-top: 1em;
}
<div class="a">
  <div class="d">
    <div class="b">hello</div>
    <div class="c">testing longer</div>
  </div>
</div>

【讨论】:

  • 啊,当然!谢谢!
  • 很高兴我能帮上忙,@RyanPeschel ?
猜你喜欢
  • 1970-01-01
  • 2019-09-14
  • 2012-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多