Last Items Won't Absolute Position

Kristen

New Member
#1
I have been teaching myself HTML/CSS and realized CSS positioning has stumped me. I made myself a basic exercise to play around with and help me understand. (It is containing 4 sections, labeled 1-4.) I can get sections 1-3 to absolute position themselves to the top of the relative container body, but section 4 refuses to absolute position itself. However, if I move section 4 after section 2 in the html (so it isn't last), it works fine. So basically, just the last section will not work. Sorry if this is confusing. Still learning, so still learning what I am talking about! If anyone can shine some light on what I am doing, I would be forever grateful! Thank you!
Mã:
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;
}
Mã:
<section id="section1">Section 1</section>
<section id="section2">Section 2</section>
<section id="section3">Section 3</section>
<section id="section4">Section 4</section>
 

Admin

Administrator
Thành viên BQT
#2
I made some changes and here is the explanation. You can add position: absolute to section in the CSS so all the <section> in the HTML have absolute positioning.

When you put position: relative in #section1, #section2, #section3, and #section4, you changed the positioning of <section> from absolute to relative, and you don't want to do that in this case.

Once you have that, then you can play around with the top, bottom, left, right to see how each <section> stacks on each other.

I have section1 at 0px from top , 0px from left relative to the container.

section2 at 20px from top, 20px from left relative to the container.

section3 at 40px from top, 40px from left relative to the container.

section4 at 60px from top, 60px from left relative to the container.

Because we don't define z-index, so in the HTML code the later <section> will be on top of the previous <section>.

Mã:
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;

}
Mã:
<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>
 
Top