CSS - 以元素自身宽度的百分比定位元素

新手上路,请多包涵

我想将元素的中心(无论其高度如何)定位在其父元素的底部。我以为我会选择绝对但没有任何意义。见下图:

在此处输入图像描述

 <div id="red">
    <div id="blue"></div>
</div>

我怎样才能得到这个结果?

编辑:感谢@Gaby aka G. Petrioli 我找到了我的解决方案:

 #red{
  width: 300px;
  height: 200px;
  background: red;
  position:relative;
}
#blue{
  width: 100px;
  height: 50px;
  background: blue;
  right:3%;

  /* here is the magic solution*/
  position:absolute;
  bottom: 0;
  transform: translateY(50%);
}
 <div id="red">
        <div id="blue"></div>
    </div>

原文由 Marine Le Borgne 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 414
2 个回答

您应该使用绝对位置将它放在底部,然后使用转换平移将它向上移动 50%,因为它是根据它自己的高度工作的。

所以

.red{position:relative}
.blue{
   position:absolute;
   top:100%;
   right:50px;
   transform:translateY(-50%);
}

原文由 Gabriele Petrioli 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以使用 CSS Positioning ,例如:

 .red {
  position: relative;
}

.blue {
  position: absolute;
  top: 100%; // Will be at exact bottom
  left: 50%;
  transform: translate(-50%, -50%); // Will pull 50% (of blue) upwards & 50% from the right as well
}

 .red {
  background: red;
  width: 200px;
  height: 300px;
  position: relative;
}

.blue {
  background: blue;
  width: 100px;
  height: 200px;
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translate(-50%, -50%);
}
 <div class="red">
  <div class="blue"></div>
</div>

希望这可以帮助!

原文由 Saurav Rastogi 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题