如何将绝对定位的div保持在可调整大小的可拖动容器div的中心?

时间:2011-02-10 15:08:01

标签: jquery css

<!--container with jQuery UI draggable , resizable plugins applied-->
<div class="container">
  <div class="stayInCenter" style="position:absolute;width:300px; height:400px">
      I will aways stay in center of the container no matter where you are
      and how big or small you become
  </div> 
</div>

2 个答案:

答案 0 :(得分:3)

如果您不需要垂直居中:

.container .stayInCenter {      
  position:relative; /* Not absolute */
  margin:0 auto      /* Make the left/right be centered */
}

如果您确实需要垂直居中:

.container .stayInCenter {      
  position:absolute;

  /* Move to the center of the positioned parent */
  left:50%; top:50%;

  /* Give a fixed size */
  width: 300px; height: 400px;

  /* Move backwards by half the size, so the center is at 50% */
  margin-left:-150px; margin-top:-200px;
}

另外,don't mix CSS with your HTML

答案 1 :(得分:0)

你放一个固定的宽度,让我们说'宽度:500px'
并且你把'margin:auto'

如果你需要一个上边距,你可以写例如。 'margin:auto'之后的'margin-top:100px'

应该做的工作