2

I tried to position div absolute to its parent. See chart1.

I set left and top properties, but the div is still positioned to root element, not its parent element dashboard.

What am I missing here, please?

#nav {
  width: 200px;
  min-height: 500px;
  border: 2px solid gray;
  display: inline-block;
}

#chart1 {
  position: absolute;
  top: 20px;
  left: 100px;
  width: 250px;
  height: 450px;
  border: 1px solid black;
}

#chart2 {
  position: absolute;
  top: 20px;
  left: 450px;
  width: 250px;
  height: 450px;
  border: 1px solid black;
}
<div id="nav"></div>
<div id="dashboard">
  <div id="chart1">Chart 1</div>
  <div id="chart2">Chart 2</div>
</div>
Karl
  • 854
  • 9
  • 21
nm114
  • 23
  • 2
  • give Div parent relative – Joykal Infotech Apr 25 '19 at 11:42
  • 1
    _“What am I missing here, please?”_ - absolute basics, that you could and should go read up on in any CSS beginner’s tutorial … And even just typing your question title into Google verbatim would have immediately lead you to explanations such as https://tomelliott.com/html-css/css-position-child-div-parent – 04FS Apr 25 '19 at 11:43
  • Solved. Thank you all for your kind help. – nm114 Apr 25 '19 at 12:02

2 Answers2

4

you are missing position: relative. parent div should have position relative and child div should have a position absolute

#nav {
  width: 200px;
  min-height: 500px;
  border: 2px solid gray;
  display: inline-block;
}
#dashboard {
  position: relative;
}
#chart1 {
  position: absolute;
  top: 20px;
  left: 100px;
  width: 250px;
  height: 450px;
  border: 1px solid black;
}

#chart2 {
  position: absolute;
  top: 20px;
  left: 450px;
  width: 250px;
  height: 450px;
  border: 1px solid black;
}
<div id="nav"></div>
<div id="dashboard">
  <div id="chart1">Chart 1</div>
  <div id="chart2">Chart 2</div>
</div>
Vikas Rinvi
  • 1,158
  • 12
  • 28
0

position: relative is the key.

#nav {
  width: 200px;
  min-height: 500px;
  border: 2px solid gray;
  display: inline-block;
}
#dashboard {
  position: relative;
}
#chart1 {
  position: absolute;
  top: 20px;
  left: 100px;
  width: 250px;
  height: 450px;
  border: 1px solid black;
}

#chart2 {
  position: absolute;
  top: 20px;
  left: 450px;
  width: 250px;
  height: 450px;
  border: 1px solid black;
}
<div id="nav"></div>
<div id="dashboard">
  <div id="chart1">Chart 1</div>
  <div id="chart2">Chart 2</div>
</div>
Joykal Infotech
  • 1,840
  • 3
  • 9
  • 17