如何将元素置于绝对位置的元素下?

时间:2017-11-02 10:29:38

标签: javascript jquery html css

这是我的代码:



.absolute_postion{
  position: absolute;
  border: 1px solid red;
  height: 30px;
  width: 100%;
  clear: both;
  
}

.other_elements{
  border: 1px solid green;
  height: 30px;
  width: 100%;
}

<div class="wrapper">
  <div class="absolute_postion">foo</div>
  <div class="other_elements">bar</div>
</div>
&#13;
&#13;
&#13;

如您所见,div.other_elements位于div.absolute_postion之下。如何将其放在div.absolute_postion的底部?

3 个答案:

答案 0 :(得分:1)

top:0提交至.absolute_postion课程,将margin-top:30px提交至.other_elements

.absolute_postion{
  position: absolute;
  border: 1px solid red;
  height: 30px;
  width: 100%;
  clear: both;
  top:0;  
}

.other_elements{
  border: 1px solid green;
  height: 30px;
  width: 100%;
  margin-top:30px;
}
<div class="wrapper">
  <div class="absolute_postion">foo</div>
  <div class="other_elements">bar</div>
</div>

答案 1 :(得分:1)

我看到.absolute_postion元素的高度是动态的,所以你可以用jquery实现这个 您可以使用height()方法获取div的像素,并将margin-top应用于该值:

var val = $('.absolute_postion').height()
$('.other_elements').css('margin-top', val);
console.log(val)
.absolute_postion{
  position: absolute;
  border: 1px solid red;
  height: 30px;
  width: 100%;
  clear: both;
  top:0; 
}

.other_elements{
  border: 1px solid green;
  height: 30px;
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="absolute_postion">foo</div>
  <div class="other_elements">bar</div>
</div>

  

注意:请记住将top:0添加到a​​bsolute_postion div。

答案 2 :(得分:0)

添加上边距等于absolute_position div

的高度

&#13;
&#13;
.absolute_postion {
  position: absolute;
  border: 1px solid red;
  height: 30px;
  width: 100%;
  clear: both;
  top: 0;
}

.other_elements {
  border: 1px solid green;
  height: 30px;
  width: 100%;
  margin-top: 32px;
}
&#13;
<div class="wrapper">
  <div class="absolute_postion">foo</div>
  <div class="other_elements">bar</div>
</div>
&#13;
&#13;
&#13;