div with position:absolute (for parent position:relative ), with top:0 , with left:0 indented at the top (not counting the standard margin the body ).

But if you remove the paragraph, the div will be without this indent.

Why is that?


 body { position: relative; font-family: Arial; } div { position: absolute; top: 0; left: 0; margin: 0; border: 1px solid gray; background: white; color: black; padding: 5px; } 
 <p>paragraph paragraph paragraph paragraph</p> <div>div div</div> 

  • For body tag position: relative style required? - Alexan-Dwer
  • Must be reset - * {margin: 0;} - soledar10
  • That's how it will be jsfiddle.net/9vaoy63g without position: relative for body - Alexan-Dwer

3 answers 3

Because by default, not only <body> has indents, but <p> , for example - which pushes <body> down, which means that the absolutely positioned div behind them.

  • In the sense of? How can a paragraph move the body down? - Sergey Razumov
  • The top margin of the first nested block extends beyond the parent block — that is how it can. The page structure is html> body> p, the body has margins of 8px by default, they move the body away from html, the 1.5em section - when it's first, the body starts moving away not by 8px, but by 1.5em. - Sasha Omelchenko pm

Zero margin and padding

 *{ margin:0; padding:0; } 
  • And if I need to indent a paragraph? So the result will be the same. - Sergey Razumov
  • body must be removed position: relative; - Sergey B

You just need to zero margin and padding :

 .class{ margin: 0; padding: 0 } 

UPD - this is due to the fact that some elements have their own "default" padding or margin . In such cases, it is usually reset, and this is higher :)

  • And if I need to indent a paragraph? So the result will be the same. - Sergey Razumov
  • Then add a margin-bottom paragraph. - user218976
  • I need an indent from above. - Sergey Razumov