绝对定位:为什么我的盒子会偏移?

问题描述 投票:0回答:1

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

背景。

我正在开发一个相当复杂的网站,我有一个显示的想法,包括一系列的盒子,可以在屏幕上产生。由于太过复杂的原因,在此无法解释,我决定组织这些盒子的最佳方式是通过我的HTML中的父子结构。这是因为将子 div 的位置值设置为 100% 远离(Top、Left、Right、Bottom)是让方框不重叠的好方法。

这是我的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>

有谁知道为什么我的每一个盒子都偏移了顶值?是不是和边距有关?

下面是我说的一个图片。

请在这里输入图片描述

html css web css-position absolute
1个回答
2
投票

原因是由于 top: 0%. 如果你把它去掉,它就会并排排列。原因是top属性将元素的顶边设置为从其父容器的顶边向下0%。父容器有一个位于其自身外侧的边框,这就是为什么它看起来像有一个层叠效果。边框的底部是元素的顶边。

https:/www.w3schools.comcssrefpr_pos_top.asp

© www.soinside.com 2019 - 2024. All rights reserved.