【问题标题】:Position ''top/bottom'' takes the image out of the divPosition ''top/bottom'' 将图像从 div 中取出
【发布时间】:2020-09-16 10:43:58
【问题描述】:

这可能有点提前,但我无法在任何地方得到答案,我开始生气了。

我设法按照我想要的百分比值来定位我的云,因此它们与视口/设备屏幕成比例。我的 div 有相对位置,所以里面的图像(它们都有绝对位置)可以相对于包装容器(div)在里面移动

但是,如果我更改或添加 topbottom 位置百分比值到我的图像,图像会以某种方式移出父 div(使用 position: relative),所以,如果我更改 padding在我的包装 div 中(因此它可以覆盖屏幕的更多区域),图像不受影响,它们不会沿着 div 填充的变化移动,就好像它们没有嵌套在我的 div 中一样。

有谁知道具体是怎么回事?

<div class="top-container">
    <img class="top-cloud">
    <h1>I'm Marcos</h1>
    <h2>A Software Developer</h2>
    <img class="bot-cloud">
    <img class="mountain">
</div>

这是我的 CSS

body {
    margin: 0;
    text-align: center;
}

h1 {
    margin-top: 0;
}

.top-container {
    background-color: #79bac1;
    position: relative;
    padding: 10% 0 0 0;
}

.top-cloud {
    position: absolute;
    width: 8%;
    left: 15%;
}

.mountain {
    width: 35%;
    display: block;
    margin: auto;
}

.bot-cloud {
    position: absolute;
    width: 8%;
    right: 15%;
    top: 10% /*If I delete this value, the image (.bot-cloud) moves in and it gets affected by the ".top-container" padding. But if I leave it, and modify the padding in the ".top-container", it gets moved out of the ".top-container" as if it's not wrapped by it.*/
}

【问题讨论】:

  • 如果没有可用的图像,很难看到会发生什么,但乍一看我会说你的top-cloud 需要一个top 属性,而你的bot-cloud 需要一个bottom 属性而不是top。不确定.mountain { margin: auto } 的效果是什么,因为它是云的兄弟,具有相同的z-index,它可能会将它们推到一边。因此,请使图像可用或至少提供它们的物理宽度和高度值。

标签: css containers css-position padding


【解决方案1】:

您的图像有 position: absolute; ,它将它从文档流中取出,即它不会占用任何如果您只是删除它就不会存在的空间 - 它只覆盖其他元素的空间。

它在位置方面的唯一参考是具有position: relative的下一个最高元素。如果top0,则其顶部将直接位于父级的顶部边框。父级的padding 根本不会改变这一点(参见下面的sn-p)。

如果您使用负的 top 值,它将(垂直)移动 父级(=向上),例如 top: -10% 将其放置在 10%(父级高度) 上方(= 外部)父级的上边框。像top: 10% 这样的正值会将其放置在父级顶部边框低于(= 内部)的10%(父级高度)。 top 的引用始终是父元素的上边框。 leftrightbottom 值的原理相同 - 它们的引用将是相对父级的左、右和下边框。

body {
  margin: 0;
  text-align: center;
}

h1 {
  margin-top: 0;
}

.top-container {
  background-color: #79bac1;
  position: relative;
  padding: 10% 0 0 0;
}

.top-cloud {
  position: absolute;
  width: 8%;
  left: 15%;
}

.mountain {
  width: 35%;
  display: block;
  margin: auto;
}

.bot-cloud {
  position: absolute;
  width: 8%;
  right: 15%;
  top: 0%;/*If I delete this value, the image (.bot-cloud) moves in and it gets affected by the ".top-container" padding. But if I leave it, and modify the padding in the ".top-container", it gets moved out of the ".top-container" as if it's not wrapped by it.*/
}
<div class="top-container">
  <img class="top-cloud">
  <h1>I'm Marcos</h1>
  <h2>A Software Developer</h2>
  <img src="https://placehold.it/200x150/d66" class="bot-cloud" >
  <img src="https://placehold.it/150x100/6a9" class="mountain">
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-27
    • 2015-05-11
    • 1970-01-01
    • 2015-01-13
    • 2021-08-03
    • 2010-09-22
    • 2014-07-06
    相关资源
    最近更新 更多