我试图将div绝对位置为其父级。参见图1。
我设置了left和top属性,但是div仍然定位到根元素,而不是其父元素仪表板。
请问我在这里想念什么?
#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>
答案 0 :(得分:3)
您缺少position: relative
。
父div应该具有相对位置,子div应该具有绝对位置
#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>
答案 1 :(得分:0)
position: relative
是关键。
#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>