Sign in
Log inSign up
Position: absolute

Position: absolute

Eze Bernardine May's photo
Eze Bernardine May
·Dec 18, 2018

position: absolute;

Tips

  • The element is removed from the normal document flow,
  • no space is created for the element in the page layout.
  • Well, it is positioned based on its closest ancestor with a position other than static.
  • If there is not an ancestor that fits the criteria, it is positioned relative to the body element.

Note: body can be scrolled unlike viewport

Effect of top, bottom, left and right on it

You use the positioning attributes top, left, bottom. and right to set the location.

Remember that these values will be relative to the next parent element with relative (or absolute) positioning. If there is no such parent, it will default all the way back up to the <html> element itself meaning it will be placed relatively to the page itself.

Quick, let’s look at the code

body {
margin: 0;
height: 1000px;
background-color: azure;
}

section {
border: 1px solid rgb(225, 255, 0);
margin: 100px auto;
width: 500px;
padding: 10px;
background-color: crimson;
}

h1 {
height: 50px;
width: 50px;
margin: 2px;
background: green;
font-size: 40px;
color: antiquewhite;
}

The Html code

<section>
  <h1>1</h1>
  <h1>2</h1>
  <h1>3</h1>
</section>

<section class="section2">
  <div>
    <h1>4</h1>
    <h1 class="div5">5</h1>
    <h1>6</h1>
  </div>
</section>

absolute1.png

When div5 is given position absolute

.div5 {
background-color: tan;
position: absolute;
top: 20px;
left: 1px;
}

Since there is no immediate parent with position: absolute or relative, The absolute position of div5 will be relative to the html tag

absolute2.png

But when an immediate parent is assigned position: absolute or relative

div {
position: relative;
background-color: yellowgreen;
}

The position: absolute for div5 will be in relation to the immediate parent which is the div

absolute3.png

Also if the parent with the position: absolute or relative is the section2, and NOT the immediate div, div5’s position absolute will be in relation to section2 and not the div.

div {
/* position: relative; */
background-color: yellowgreen;
}
section:nth-child(2) {
 position: relative;
 }

absolute4.png

Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct