最后一项不会有绝对位置

Last items won't have an absolute position

我一直在自学 HTML/CSS 并意识到 CSS 定位让我很困惑。 (它包含 4 个部分,标记为 1-4。)我可以让第 1-3 部分绝对定位到相关容器主体的顶部,但第 4 部分拒绝绝对定位自己。

但是,如果我在 HTML 中将第 4 节移到第 2 节之后(所以它不是最后一个),它工作正常。所以基本上,只有最后一部分是行不通的。对不起,如果这令人困惑。

body {
  position: relative;
  width: 700px;
  height: 200px;
}

section {
  width: 25%;
  height: 25%;
}

#section1 {
  background-color: yellow;
  position: relative;
}

#section2 {
  background-color: red;
  position: relative;
}

#section3 {
  background-color: green;
  position: relative;
}

#section4 {
  background-color: aqua;
  position: absolute;
  color: white;
}
<section id="section1">Section 1</section>
<section id="section2">Section 2</section>
<section id="section3">Section 3</section>
<section id="section4">Section 4</section>

如果您尝试将每个子元素放置到特定的 绝对 位置,请尝试将其父元素 <body> relative 和子元素 <section> absolute。然后指定它们的 toprightbottomleft 值。

body
{
    position: relative;
    width: 200px;
    height: 200px;
}

section {
    width: 50%;
    height: 50%;
    position: absolute;
}

#section1 {
    background-color: yellow;
    left: 0;
    top: 0;
}
#section2 {
    background-color: red;
    left: 50%;
    top: 0;
}
#section3 {
    background-color: green;
    left: 0;
    top: 50%;
}
#section4 {
    background-color: aqua;
    left: 50%;
    top: 50%;
    color: white;
}
<head>
    <title>UNDERSTANDING POSITIONING</title>
    <link rel="stylesheet" href="main.css">
</head>  
<body>
    <section id="section1">Section 1</section>
    <section id="section2">Section 2</section>
    <section id="section3">Section 3</section>
    <section id="section4">Section 4</section>
</body>

我做了一些修改,这里是解释。您可以在 CSS 中添加 position: absolutesection,这样 HTML 中的所有 <section> 都具有绝对定位。

当您将 position: relative 放入 #section1#section2#section3#section4 时,您将 <section> 的位置从absoluterelative,在这种情况下您不想这样做。

一旦你有了它,你就可以尝试 top, bottom, left, right 看看每个 <section> 是如何相互叠加的。

我有 section1 距顶部 0px,距容器左侧 0px。

section2 距容器顶部 20 像素,距左侧 20 像素。

section3 距顶部 40 像素,距容器左侧 40 像素。

section4 距顶部 60 像素,相对于容器左侧 60 像素。

因为我们没有定义z-index,所以在HTML代码中后面的<section>会在前面的<section>之上。

body
{
    position: relative;
    width: 700px;
    height: 200px;
}

section {
    width: 25%;
    height: 25%;
    position: absolute;
}

#section1 {
    background-color: yellow;
}
#section2 {
    background-color: red;
    top: 20px;
    left: 20px;
}
#section3 {
    background-color: green;
    top: 40px;
    left: 40px;
}
#section4 {
    background-color: aqua;
    color: white;
    top: 60px;
    left: 60px;

}
<head>
    <title>UNDERSTANDING POSITIONING</title>
    <link rel="stylesheet" href="main.css">
</head>  
<body>
    <section id="section1">Section 1</section>
    <section id="section2">Section 2</section>
    <section id="section3">Section 3</section>
    <section id="section4">Section 4</section>
</body>