【问题标题】:Absolute positioning: why are my boxes offset?绝对定位:为什么我的盒子偏移了?
【发布时间】:2020-05-14 02:19:20
【问题描述】:

这似乎是一个相当基本的问题,但我只是想弄清楚。

上下文:

我正在开发一个相当复杂的网站,我的一个展示想法包括一系列可以在屏幕上生成的框。由于过于复杂无法在这里解释的原因,我决定组织这些框的最佳方式是通过我的 HTML 中的父子结构。这是因为将子 div 的位置值设置为 100% 远(上、左、右、下)是使框细分而不重叠的好方法。

这是我的 HTML:

.box-1,
.box-2,
.box-3,
.box-4 {
    display: flex;
    border: solid black;
    justify-content: center;
    align-items: center;
}

.box-1 {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 150px;
    height: 150px;
    border: solid rgb(72, 255, 72);
    border-width: 3px;
}

.box-2 {
    position: absolute;
    top: 0%;
    left: 100%;
    width: 150px;
    height: 150px;
    border: solid rgb(255, 72, 72);
    border-width: 3px;
}

.box-3 {
    position: absolute;
    top: 0%;
    left: 100%;
    width: 150px;
    height: 150px;
    border: solid rgb(218, 255, 56);
    border-width: 3px;
}

.box-4 {
    position: absolute;
    top: 0%;
    left: 100%;
    width: 150px;
    height: 150px;
    border: solid rgb(112, 86, 255);
    border-width: 3px;
}
<!DOCTYPE html>

<html>

<head>
  <meta http-equiv="content-type" content "text/html; charset=UTF-8"/>
  <link rel="stylesheet" type="text/css" href="styles.css">
</head>

<body>
  <div class="box-1">
    box1
    <div class="box-2">
      box2
      <div class="box-3">
        box3
        <div class="box-4">
          box4
        </div>
      </div>
    </div>
  </div>

</body>


</html>

有谁知道为什么我的每个盒子都在顶部偏移?这可能与利润有关吗?

这是我正在谈论的内容的图片:

enter image description here

【问题讨论】:

    标签: html css web css-position absolute


    【解决方案1】:

    原因是因为top: 0%。如果删除它,它将并排对齐。推理是因为 top 属性将元素的上边缘设置为从其父容器的上边缘向下 0%。父容器有一个位于其自身外部的边框,这就是为什么它看起来像您具有级联效果的原因。边框的底部是元素的上边缘。

    https://www.w3schools.com/cssref/pr_pos_top.asp

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-21
      • 1970-01-01
      • 2020-02-13
      相关资源
      最近更新 更多