PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 18, 2022

[FIXED] Why when I set the body to position: relative, I get unexpected behavior

 July 18, 2022     css, document-body, html     No comments   

Issue

Any css masters know why this is happening? Or can explain it? The p is being hoisted to behave like it is inside the div by adding position relative to body. I know position:static happens to the body by default, but when I set it to relative, the p tag behaves like it is nested inside the div tag. Anyone knows why this behavior is happening?

body {
    background-color: purple;
    margin: 0px;
    padding: 0px;
    position: relative;


}

div {
    background-color: red;
    height: 100px;
    position: relative;
    margin:0px;
    padding: 0px;

}


p {
    background-color: blue;
    position: absolute;
    bottom: 0px;
    margin:0px;
}
<!DOCTYPE html>
<html>
  <body>
        <div>
        <!-- it behaves like if it was here -->
        </div>
        <p>Hello World</p>
  </body>
</html>


Solution

The p is positioned at the bottom of its containing block

If the element has 'position: absolute', the containing block is established by the nearest ancestor with a 'position' of 'absolute', 'relative' or 'fixed', in the following way:

...

If there is no such ancestor, the containing block is the initial containing block.

and the "initial containing block" is

The containing block in which the root element lives is a rectangle called the initial containing block. For continuous media, it has the dimensions of the viewport and is anchored at the canvas origin; it is the page area for paged media.

So without position:relative on body, the element is placed at the bottom of the screen. with position:relative at the bottom of the body.

add border to the body element to see its boundary. The coloration is confusing you due to another feature which is background propagation

body {
  background-color: purple;
  margin: 0px;
  padding: 0px;
  position: relative;
  border:2px solid green;
}

div {
  background-color: red;
  height: 100px;
  position: relative;
  margin: 0px;
  padding: 0px;
}

p {
  background-color: blue;
  position: absolute;
  bottom: 0px;
  margin: 0px;
}
<!DOCTYPE html>
<html>

<body>
  <div>
    <!-- it behaves like if it was here -->
  </div>
  <p>Hello World</p>
</body>

</html>



Answered By - Temani Afif
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing